使用 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>'
})
View Code

 

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,1);
    }
  }

}
</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>
View Code

 

4 父子組件之間傳遞消息的方式和之前的博文一致。參看

Vue 中組件概念

 

5 最后的效果如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM