lac bin push content 技术 delete 列表组 for spa
二、综合组件之间的通信
实现一个ToDoList。
①完成所有的组件的创建和使用
②add
点击add按钮时候,将用户输入的内容(todoinput),显示在(todolist)
核心代码:兄弟组件间通信
步骤1:var bus = new vue()
步骤2:在准备接受数据的组件
bus.$on(‘addEvent‘,function(){
})
步骤3:触发事件
bus.$emit(‘addEvent‘,123)
将todolist中数组的元素 渲染在todoitem的每一个span标签。(父子组件通信)
③delete
在todoitem中点击delete按钮时,将该todoitem删除,由于todoitem的数量 取决于 todolist中数组
子组件 和 父组件通信、
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Title
- </title>
- <script src="js/vue.js">
- </script>
- <script src="js/vue-resource.js">
- </script>
- </head>
- <body>
- <div id="container">
- <p>
- {{msg}}
- </p>
- <todobox>
- </todobox>
- </div>
- <script>
- < !--兄弟间通信-->
- var bus = new Vue();
- // input组件
- Vue.component("todoinput", {
- // 保存用户输入的数据
- data: function() {
- return {
- userInput: ""
- }
- },
- methods: {
- sendInput: function() {
- // 触发自定义事件,将this.userInput这个传递到todolist
- bus.$emit("addEvent", this.userInput);
- this.userInput = "";
- }
- },
- template: ` < div > <h1 > 待做事项 < /h1>
- <input type="text" placeholder="健身" v-model="userInput"/ > <button@click = "sendInput" > Add < /button>
- </div >
- `
- })
- // 列表组件
- Vue.component("todolist", {
- // 保存传递来的用户输入的数据
- data: function() {
- return {
- inputList: []
- }
- },
- beforeMount: function() {
- // 触发绑定
- // msg就是事件触发后传递过来的数据
- //var that = this;
- bus.$on("addEvent", (msg) = >{
- // 保存到数组inputList中
- this.inputList.push(msg);
- })
- },
- template: ` < div > <ul > <todoitem v - bind: content = "tmp"v -
- for = "(tmp,index) in inputList"v - bind: key = "index"v - bind: myIndex = "index" > </todoitem>
- </ul > </div>
- `
- / / 出现警告,加下标,提高列表渲染
- })
- // item组件
- Vue.component("todoitem", {
- // props子组件获取父组件的数据,将todolist中的内容以及内容的下标获取
- props: ["content", "myIndex"],
- methods: {
- // 通过下标删除
- deleteList: function() {
- this.$parent.inputList.splice(this.myIndex, 1);
- }
- },
- template: ` < div > <li > <button@click = "deleteList" > delete < /button>
- <span>{{content}}</span > </li>
- </div > `
- })
- //根组件
- Vue.component("todobox", {
- template: ` < div > <todoinput > </todoinput>
- <todolist></todolist > </div>
- `
- })
- new Vue({
- el: "#container",
- data: {
- msg: "Hello Vue"
- }
- })
- /
- </script>
- </body>
- </html>
vue--综合组件间的通信
lac bin push content 技术 delete 列表组 for spa
原文:http://www.cnblogs.com/wangruifang/p/7779419.html
来源: http://www.bubuko.com/infodetail-2378879.html