2021-7-12 VUE的组件认识

VUE组件简单实例

<!DOCTYPE html>
<html>
<head>
    <title>        
    </title>
</head>
<body>
<div id="app">
  <div>
    <bt></bt>
    <bt></bt>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript"></script>
<script type="text/javascript">
Vue.component('bt',{
  data:function(){
    return{
      count:0
    }
  },
  template:'<button @click="count++">{{count}}</button>'
});
new Vue({
  el:'#app',
  data:{}
});
</script>
</body>
</html>
View Code

 模板使用的注意事项

data必须是一个函数

<!DOCTYPE html>
<html>
<head>
    <title>        
    </title>
</head>
<body>
<div id="app">
  <div>
    <bt></bt>
    <bt></bt>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript"></script>
<script type="text/javascript">
Vue.component('bt',{
  data:function(){
    return{
      count:0
    }
  },
  //template:'<div><button @click="count++">{{count}}</button><button>你好呀</button></div>'//在使用多个标签时要添加一个根节点
  //使用模板字符串可以让模板可读性更好一些
  template:`<div>
  <button @click="count++">{{count}}</button>
  <button>你好呀</button>
  </div>`
});
new Vue({
  el:'#app',
  data:{}
});
</script>
</body>
</html>
View Code

 组件命名

<!DOCTYPE html>
<html>
<head>
    <title>        
    </title>
</head>
<body>
<div id="app">
  <div>
    <bt></bt>
    <bt></bt>
    <h-w></h-w>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript"></script>
<script type="text/javascript">
Vue.component('HW',{//驼峰式命名,只能在模板中使用,不能在标签页中使用,如果要用的话要用小写加-,如上
  data:function(){
    return {
      y:0
    }
  },
  template:`
  <button>hehe</button>
  `
});
Vue.component('bt',{
  data:function(){
    return{
      count:0
    }
  },
  //template:'<div><button @click="count++">{{count}}</button><button>你好呀</button></div>'//在使用多个标签时要添加一个根节点
  //使用模板字符串可以让模板可读性更好一些
  template:`<div>
  <button @click="count++">{{count}}</button>
  <button>你好呀</button>
  <HW></HW>
  </div>`
});
new Vue({
  el:'#app',
  data:{}
});
</script>
</body>
</html>
View Code

 局部组件的定义,要在components中用-命名注册

<!DOCTYPE html>
<html>
<head>
    <title>        
    </title>
</head>
<body>
<div id="app">
  <div>
    <h-w></h-w>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script type="text/javascript"></script>
<script type="text/javascript">
var HW={
  data:function(){
    return{
      ss:'ss'
    }
  },
  template:`
  <span>{{ss}}</span>
  `
}
new Vue({
  el:'#app',
  data:{},
  components:{
    'h-w':HW
  }
});
</script>
</body>
</html>
View Code

 

posted @ 2021-07-12 17:06  月长生  阅读(38)  评论(0)    收藏  举报