1. 程式人生 > 其它 >(2)vue的元件化開發

(2)vue的元件化開發

1.註冊組建的基本步驟

元件的使用分成三個步驟:1.建立元件構造器2.註冊元件3.使用元件

2.全域性元件和區域性元件

當我們通過呼叫Vue.component()註冊元件時,元件的註冊是全域性的
這意味著該元件可以在任意Vue示例下使用。
 如果我們註冊的元件是掛載在某個例項中, 那麼就是一個區域性元件

3.vue元件模板分離寫法(以後開發常用這種寫法)

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <hello></hello>
  </div>
</template>

<script>
import Hello from 
'./components/Hello' export default { name: 'app', components: { Hello } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; }
</style>

4.父子元件之間的通訊

(1)子元件是不能直接引用父元件或者Vue例項的資料的

(2)父元件向子元件傳值:父元件通過屬性的方式將值傳遞給子元件,子元件內部通過props接收傳遞過來的值

(3)子元件向父元件傳事件:子元件通過自定義事件向父元件傳遞資訊,父元件監聽子元件事件

注意:props屬性名的規則,在props中使用駝峰的形式,則在模板中需要使用短橫線的形式。

元件的data屬性必須是一個函式。

父傳子:

<!--父元件-->
 <template>
   <div>
    <h2>父元件</h2>
    <Child-one :parent-message="parentMessage"></Child-one>
   </div>
 </template>

 <script>
  import ChildOne from './ChildOne';
  export default{
name:"ParentOne", components: { ChildOne }, data() { return { parentMessage: '我是來自父元件的訊息' } } } </script> <style scoped></style>
<!--子元件-->
 <template>
   <div>
     <h3>我是子元件一</h3>
     <span>{{parentMessage}}</span>
   </div>
 </template>

 <script>
  export default{
   name:"ChildOne",
   props: {
parentMessage:{ type:String, default:true
} } } </script> <style scoped></style>

子傳父:

<!--父元件-->
 <template>
   <div>
     <h2>父元件</h2>
     <Child-one @childEvent="parentMethod"></Child-one>
   </div>
 </template>

 <script>
  import ChildOne from './ChildOne';
  export default{
    components: {
      ChildOne
   },
   data() {
      return {
        parentMessage: '我是來自父元件的訊息'
       }
   },
   methods: {
      parentMethod(name, age ) {
       console.log(this.parentMessage, {name, age});
        }
     }
  }
 </script>
 <style scoped>
 </style>
 


 <!--子元件-->
 <template>
    <div>
      <h3>子元件</h3>
    </div>
 </template>
 <script>
    export default{
      mounted() {
        this.$emit('childEvent', { name: 'zhangsan', age: 10 });
      }
  }
 </script>
 <style scoped></style>

5.父子元件間的訪問方式(瞭解)

父元件訪問子元件:使用$children(訪問全部子元件)或$refs(訪問部分子元件)

子元件訪問父元件:使用$parent

6.非父子元件通訊

可以用vuex的store來管理狀態,在你的專案中用store來管理加入購物車的物品資訊,實現了詳情頁和購物車頁的通訊,多做專案去體會

7.插槽slot

我們定義的元件通常會被用到各個地方,但是並不一定能夠滿足所有的使用場景,有時候我們需要
進行一些功能的擴充套件。這時候就需要用到slot了。一句話描述slot:就是用來在元件中插入新的內容
例如:

Child.vue中使用slot

<template>
  <div class="container">
    姓名:{{name}}
    年齡:{{age}}
    <button @click ="$emit('onClick','自定義事件')" :class = "type">點選</button>
    <slot></slot>
  </div>
</template>

Parent.vue中擴充套件功能。插入一段話:

<template>
  <div class="container">
    <Child @onClick = 'handleClick' :age = age :type = type>
      <div>這是通過slot插入的一段話</div>
    </Child>
  </div>
</template>

如上所示:在Child.vue中使用了slot,在Parent.vue中使用Child時,插入了一段話。
實現了功能的擴充套件。當然如果需要擴充套件更多的功能可以使用具名插槽。

8.具名插槽