使用 vue-cli 实现组件之间数据交换

1 使用脚手架工具用 webpack 模板初始化项目,用 webstorm 打开项目。src 目录下是要编写的源文件。

main.js 文件 是主入口文件,

在es6语法中,:function(){}可以简写为(){}

在vue-cli中定义data时,不再是对象,而是以function函数的形式返回对象

template模板下只能有一个子节点,否则会报错

我将 App.vue 改名为TodoList.vue 因此修改 main.js 文件,

import TodoList from './TodoList'
...
components: {
todoList:TodoList
},

main.js 文件内容如下

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import TodoList from './TodoList' Vue.config.productionTip = false /* eslint-disable no-new */
new Vue({
el: '#app',
components: {
todoList:TodoList
},
template: '<todoList></todoList>'
})

2 组件的属性内容现在写到 export default{} 对象中

在 vue 文件中将模板放在 <template> 标签下

将脚本内容放到 <script> 标签下

TodoList 组件内容如下

<template>
<div>
<input v-model="inputValue"/>
<button @click="addItem">提交</button>
<ul>
<todo-item
v-for="(item, index) of todoList"
:key="index" :content="item"
:index="index"
@deleteItem="deleteItem"
> </todo-item> </ul>
</div>
</template> <script>
import TodoItem from './components/TodoItem' export default {
components: {
'todo-item':TodoItem
},
data () {
return {
inputValue: '',
todoList: []
}
},
methods:{
addItem () {
this.todoList.push(this.inputValue);
this.inputValue= '';
},
deleteItem (index) {
this.todoList.splice(index,);
}
} }
</script> <style>
</style>

在该组件中引用了 TodoItem 组件。在本组件中需要引入该组件, 使用 components 属性,引用一个对象。该对象的键是在该组件的名称,值是引用的组件名称。

对于 components 对象中的每个属性来说,其属性名就是自定义元素的名字,其属性值就是这个组件的选项对象。

3 子组件写法和上面一样

TodoItem.vue 文件内容如下

<template>
<li v-text="content" @click="deleteItem"></li>
</template> <script>
export default {
props:['content','index'],
methods: {
deleteItem () {
this.$emit('deleteItem',this.index); }
}
}
</script> <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

4 父子组件之间传递消息的方式和之前的博文一致。参看

Vue 中组件概念

5 最后的效果如下

使用 vue-cli 实现组件之间数据交换

上一篇:java--加强之 Java5的线程并发库


下一篇:VS工具如何新建筛选器