Vue组件与实例的关系

2018-11-19  本文已影响6人  楠楠_c811

组件与实例的关系:
Vue是由一个个实例构建而成的,一个组件就是一个Vue的实例,每个组件内部都可以写属性,因此每一个组件都是一个Vue的实例。
每一个实例都有自己的template模板,如果没有,根节点就会去挂载点下面找,找到root会把root下面的所有DOM标签当做这个实例的模板使用。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>组件与实例的关系</title>
  <!-- 在head里面引入,避免闪屏问题 -->
  <script src="./vue.js"></script>
</head>
<body>
  <div id="root">
   <div> 
     <!-- v-model双向数据绑定 -->
     <input v-model="inputValue"/>
     <!-- 绑定点击事件 -->
     <button @click="handleSubmit">提交</button>
   </div>
   <ul>
     <!-- 使用组件来实现,同时绑定属性:content="item" 传参item用以达到动态展示效果 -->
     <todo-item
      v-for="(item, index) of list"
      :key="index"
      :content="item"
     ></todo-item>
   </ul>
  </div>
    
  <script>
    // 定义全局组件 
    Vue.component("todo-item",{
      // 传参后不能直接使用,必须接收一下才可以使用
      props:['content'],
      // 每一个组件都是一个实例,可以添加事件和属性
      template: '<li @click="handleClick">{{content}}<li>',
      methods:{
        handleClick: function() {
          alert("clicked")
        }
      }
    })
    new Vue({
      el:"#root",
     data:{
       inputValue:'',
       list:[],
     },
    //  添加事件
     methods:{
       handleSubmit: function(){
        // 将inputValue push到数组中
         this.list.push(this.inputValue),
        // 清空输入框
         this.inputValue=''
       }
     }
    })
  </script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读