我陷入了Vue的逻辑使用中,我有一个从ajax获取结果的“列表”组件,当我想要添加一个搜索字段时,问题就出现了,我有这样的东西:
search.vue
<template>
<div>
<div v-for="(result, index) in results">
<h2>{{ result.name }}</h2>
</div>
</div>
</template>
<script>
export default {
name : 'searchList',
data() {
return { results: [] }
}
created: function(){
this.goSearch();
},
methods : {
goSearch : function(){
this.results = axios.get('/search');
}
}
}
</script>
这就像一个咒语,重点是我想要添加一个输入到搜索中,我做了一些研究,我发现实现这一点的唯一方法是使用另一个组件,但我不想只为一个输入创建另一个组件,所以我想这样做:
index.html
<input type="text" v-model="goSearch">
<search-list></search-list>
但我面临的问题是Vue返回了一个错误:
[Vue warn]: Property or method "goSearch" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
我也尝试过使用v-bind="goSearch"
,但也不起作用。有什么想法可以做到这一点吗?
更新:我已经创建了一个按钮来调用函数:
<button @click="goSearch"></button>
函数"goSearch“现在尝试从文本框中获取值,但也不起作用。
发布于 2018-06-12 03:00:35
您会收到这样的错误,因为您正在使用:
<input type="text" v-model="goSearch">
这里,goSearch是data
,vue找不到这个数据。但你的意思是它是一种方法。Vue不是那样工作的。如果你想在其中绑定一些方法,你不需要使用v-model
。但是您需要绑定v-on:input
<input type="text" v-on:input="goSearch">
发布于 2018-06-12 03:21:45
问题是goSearch
方法是在searchList
组件内部定义的,它外部的任何东西都不知道它是什么(在本例中是input元素),因此产生了warn。
一种解决方案是在父组件中定义方法(在本例中,它看起来像是index.html),这样所有子组件都可以访问它。
您还必须将results
数组存储在父data
中,并使用props和goSearch函数将其发送到searchList
组件,如下所示:
search.vue
<template>
<div>
<div v-for="(result, index) in results" v-bind:key="index">
<h2>{{ result.title }}</h2>
</div>
</div>
</template>
<script>
export default {
name: 'searchList',
props: ['results'],
created: function () {
this.$emit('goSearch')
}
}
</script>
父组件:
<template>
<div id="app">
<button v-on:click="goSearch">Get Random Post</button>
<search-list
v-on:goSearch="goSearch"
v-bind:results="results"
></search-list>
</div>
</template>
<script>
import searchList from './components/searchList'
export default {
name: 'App',
data () {
return { results: [] }
},
components: {
searchList
},
methods: {
goSearch: function () {
const postId = Math.floor(Math.random() * (100 - 1 + 1)) + 1
fetch('https://jsonplaceholder.typicode.com/posts/' + postId)
.then(response => response.json())
.then(json => {
this.results = [json]
})
}
}
}
</script>
请记住,如果有多个组件使用该属性/方法,则需要在父组件中定义它,然后使用props
将该信息发送给子组件,子组件可以使用emit
触发该父组件的事件。
另外,请查看this answer。
https://stackoverflow.com/questions/50804325
复制相似问题