美文网首页
Vue学习笔记[3]

Vue学习笔记[3]

作者: Camilia_yang | 来源:发表于2019-04-25 22:25 被阅读0次

参考文章:http://doc.vue-js.com/v2/guide/components.html

  • 组件注册

先注册组件后初始化根实例(Vue)

// 注册
Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})
// 创建根实例
new Vue({
  el: '#example'
})

不必在全局注册每个组件,通过使用组件实例选项注册,可以使组件仅在另一个实例/组件的作用域中可用:

var Child = {
  template: '<div>A custom component!</div>'
}
new Vue({
  // ...
  components: {
    // <my-component> 将只在父模板可用
    'my-component': Child
  }
})
  • DOM模板解析说明
    由于HTML本身的限制,某些元素内只能是某些元素,例如<ul>、<ol>、<table>、<select> 这样的元素里允许包含的元素有限制,而另一些像 <option> 这样的元素只能出现在某些特定元素的内部。
<table>
  <my-row>...</my-row>
</table>

自定义组件 <my-row> 会被当作无效的内容,因此会导致错误的渲染结果。变通的方案是使用特殊的 is 特性:

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

应当注意,如果使用来自以下来源之一的字符串模板,则没有这些限制:


  • Vue组件data必须是函数的理解
    看下面2个例子
    1、
<script type="text/javascript">
    var app=new Vue({
        el:'#app',
        data:{
            isLogin: false
        }
    })
</script>

2、

var Component = function() {};
Component.prototype.data = {
    demo: 123
}
var component1 = new Component();
var component2 = new Component();
component1.data.demo = 456;
console.log(component2.data.demo); // 456

在new vue()中,data可以直接是一个对象,每一个vue组件都是一个vue实例,通过new Vue()实例化,引用同一个对象,如果data直接是一个对象的话,那么当你修改其中一个属性的时候,另外一个实例也会跟着改。这是不行的,两个实例应该有自己各自的域才对。所以data是函数时,每个实例就拥有了自己的作用域,互不干扰。

相关文章

网友评论

      本文标题:Vue学习笔记[3]

      本文链接:https://www.haomeiwen.com/subject/gzzogqtx.html