1 回答
TA贡献1880条经验 获得超4个赞
首先是你错误地使用了 v-bind,最好使用 v-model:
<input
class="rounded-l-full w-full py-6 px-6 text-gray-700 leading-tight focus:outline-none"
id="search"
type="text"
placeholder="Search"
v-model="query"
/>
当你使用 vuex 时,第二件事是更好地组织你的代码,我会这样做:
模板:
// pass the variable query to the funcion getSearchResults
<button
class="bg-blue-900 text-white rounded-full p-2 hover:bg-blue-700 focus:outline-none w-12 h-12 flex items-center justify-center"
@click="getSearchResults(query)"
>
<font-awesome-icon :icon="['fas', 'search']" />
</button>
记者:
// Only import mapActions and mapGetters
// create the variable query inside of data() for v-model
<script>
import { mapActions, mapGetters} from "vuex";
export default {
name: "Main",
data() {
return {
query:"",
};
},
computed: {
...mapGetters(["searchResult"]),
}),
},
methods: {
...mapActions(["getSearchResults"]),
},
};
</script>
VUEX:
import axios from "axios";
const state = {
results: [],
};
const getters = {
searchResult: (state) => state.results,
};
const actions = {
async getSearchResults({commit}, query) {
const res = await axios.get(
`https://www.theaudiodb.com/api/v1/json/1/search.php?s=${query}`
);
// Execute the mutation which receive the data and pass to the state
commit('returnResults', res.data.artists)
},
};
const mutations = {
returnResults: (state, results) => (state.results = results),
};
export default {
state,
getters,
actions,
mutations,
};
添加回答
举报