父组件注入数据子组件通过 props
接收子组件 emit
数据父组件通过 @
监听
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div>
<myinput @add="add" />
</div>
<div>
<mylist :list="list"/>
</div>
</div>
</body>
<script>
Vue.component('myinput', {
template: `
<div>
<input v-model="title">
<button @click="add"> add </button>
</div>
`,
data() {
return {
title: '',
}
},
methods: {
add() {
this.$emit('add', this.title)
}
}
})
Vue.component('mylist', {
template: `
<ul>
<li v-for="item in list" :key="item.id">
{{ item.title }}
</li>
</ul>
`,
props: {
list: Array
}
})
//
var app = new Vue({
el: '#app',
data: {
list: [
{
id: 1,
title: 'title1',
},
{
id: 2,
title: 'title2',
},
],
},
methods: {
add(title) {
this.list.push({
id: Math.random(),
title,
})
}
}
})
</script>
</html>