首頁  >  文章  >  web前端  >  vue.js中component怎麼用

vue.js中component怎麼用

coldplay.xixi
coldplay.xixi原創
2020-11-12 14:24:525897瀏覽

vue.js中component的使用方法:1、擴充HTML元素,封裝可重複使用的程式碼;2、元件是自訂元素,【Vue.js】的編譯器為它新增特殊功能;3 、元件也可以是原生HTML元素的形式,以is特性擴充。

vue.js中component怎麼用

【相關文章推薦:#vue.js##】

vue.js中component的使用方法:

#什麼是元件

依照慣例,引用Vue官網的一句話:

元件(Component) 是Vue.js 最強大的功能之一。元件可以擴充 HTML 元素,封裝可重複使用的程式碼。在較高層面上,元件是自訂元素,Vue.js 的編譯器為它添加特殊功能。在某些情況下,元件也可以是原生 HTML 元素的形式,以 is 特性擴充。

元件component的註冊

全域元件:

Vue.component('todo-item',{
  props:['grocery'],
  template:&#39;<li>{{grocery.text}}</li>&#39;
})
var app7 = new Vue({
  el:"#app7",
  data:{
    groceryList:[
      {"id":0,"text":"蔬菜"},
      {"id":1,"text":"奶酪"},
      {"id":2,"text":"其他"}
    ]
  }
})
<div id="app7">
  <ol>
    <todo-item
      v-for="grocery in groceryList"
      v-bind:grocery="grocery"
      v-bind:key="grocery.id">
    </todo-item>
  </ol>
</div>

局部註冊:

var Child = {
 template: &#39;<div>A custom component!</div>&#39;
}
new Vue({
 // ...
 components: {
  // <my-component> 将只在父模板可用
  &#39;my-component&#39;: Child
 }
})

DOM範本解析說明

元件在某些HTML標籤下會受到一些限制。

例如一下程式碼,在table標籤下,元件是無效的。

<table>
 <my-row>...</my-row>
</table>

解決方法是,透過is屬性使用元件

<table>
 <tr is="my-row"></tr>
</table>

應注意,如果您使用來自下列來源之一的字串模板,將不會受限

<script type="text/x-template">

JavaScript內嵌模版字串

.vue

#元件

data使用函數,避免多元件互相影響

html

<div id="example-2">
 <simple-counter></simple-counter>
 <simple-counter></simple-counter>
 <simple-counter></simple-counter>
</div>

js

var data = { counter: 0 }
Vue.component(&#39;simple-counter&#39;, {
 template: &#39;<button v-on:click="counter += 1">{{ counter }}</button>&#39;,
 data: function () {
  return data
 }
})
new Vue({
 el: &#39;#example-2&#39;
})

如上,div下有三個元件,每個元件共用一個counter。當任一個元件被點擊,所有元件的counter都會加一。

解決方法如下

js

Vue.component(&#39;simple-counter&#39;, {
 template: &#39;<button v-on:click="counter += 1">{{ counter }}</button>&#39;,
 data: function () {
  return {counter:0}
 }
})
new Vue({
 el: &#39;#example-2&#39;
})
這樣每個元件產生後,都會有自己獨享的counter。

相關免費學習推薦:

JavaScript
(影片)#######

以上是vue.js中component怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn