0👍
You’re getting such error because you’re using:
<input type="text" v-model="goSearch">
Here, the goSearch is data
and this data is not found by vue. But you meant it to be a method. Vue doesn’t work like that. You will not require to use v-model
if you want to bind some method in it. But you will need to bind v-on:input
<input type="text" v-on:input="goSearch">
0👍
The problem is that the goSearch
method is defined inside the searchList
component, anything outside of it doesn’t know what it is (in this case, the input element), hence the warn.
A solution would be defining the method in the parent component (in this case, seems like it’s index.html), so all children components can access it.
You would also have to store the results
array inside the parent data
and send it to the searchList
component using props together with the goSearch function, like so:
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>
Parent component:
<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>
Keep in mind that if more than one component uses the property/method, you need to define it in a parent component, then you send that info to the children components using props
and the children can trigger events of that parent using emit
.
Also, check out this answer.