<ol>
<li>Vuex 库的引用路径应该正确,即 vuex.js 库的路径应该指向正确的位置。</li>
<li>搜索按钮的 @click 绑定应该使用 v-on:click 替代。</li>
<li>在 v-for 循环中的 this.$store.state.todos 应该改为直接使用 todos。</li>
<li>在 mutations 中的 search 函数应该接收两个参数,即 state 和传入的搜索关键字 id,而现在只有一个参数 state。</li>
<li>在 mutations 中的 search 函数应该修改 state.id 的值,而不是直接返回过滤后的数组。</li>
<li>在 store 对象中应该有一个 getters 属性,用来定义获取 state 中数据的方法。现在代码中没有定义 getters 属性,而是在模板中直接使用了 this.$store.getters.search。</li>
<li>在 getters 中应该定义一个名为 search 的函数,用来获取过滤后的数组。现在代码中没有定义 search 函数。</li>
</ol>
<p>修改后代码如下所示:</p>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="../vue.js"></script>
		<script src="../vuex.js"></script>
	</head>
	<body>
		<div id="app">
			<h2>列表查询</h2>
			<input type="text" v-model="id">
			<button v-on:click="search">搜索</button>
			<p>搜索结果:{{filteredTodos}}</p>
			<ul>
				<li v-for="item in todos">{{item.text}}</li>
			</ul>
		</div>
		<script>
			const store=new Vuex.Store({
				state:{
					todos:[
						{id:1,text:'列表一'},
						{id:2,text:'列表二'},
					],
					id:0
				},
				mutations:{
					setId(state, id) {
						state.id = id;
					}
				},
				getters: {
					filteredTodos(state) {
						return state.todos.filter(todo => todo.id == state.id);
					}
				}
			})
<pre><code>		var vm=new Vue({
			el:'#app',
			data:{
				id:''
			},
			store,
			computed: {
				todos() {
					return this.$store.state.todos;
				},
				filteredTodos() {
					return this.$store.getters.filteredTodos;
				}
			},
			methods:{
				search(){
					this.$store.commit('setId', this.id);
				}
			}
		})
	&lt;/script&gt;
&lt;/body&gt;
</code></pre>
</html

原文地址: https://www.cveoy.top/t/topic/fjud 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录