首页  >  文章  >  web前端  >  vue.js中component怎么用

vue.js中component怎么用

coldplay.xixi
coldplay.xixi原创
2020-11-12 14:24:525898浏览

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