39.VUE学习--组件,子组件中data数据的使用,x-template模板的使用

多处引用相同组件时,操作data不会相互影响

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>vue</title>
    <link rel="stylesheet" href="">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- <script type="text/javascript" src="../js/vue.js"></script> -->

</head>
<body>
<div id="hdcms">
    <hd-news></hd-news> <!--引入模板 和new Vue()里的components里注册时的名字 hdNews 要一致-->
    <hr>
    <hd-news></hd-news>

</div>
<script type="text/x-template" id="hdNewstemplate">
    <div>
        <li v-for="(v,k) in news">{{v.id}}=>{{v.title}}  <button @click="del(k);">删除</button></li>
    </div>
</script>
<script>
    var hdNews={
        //绑定id="hdNews" 的 x-template模板
        template:'#hdNewstemplate',
        data(){
            return {
                news:[
                    {id:0,title:'tpshop'},
                    {id:1,title:'hdcms'}
                ],
            }
        },
        methods:{
            del(k){
                console.log(k);
                this.news.splice(k,1)
            }
        }
    }
    new Vue({
        el:'#hdcms',
        //绑定组件hdNews  hdNews:hdNews简写成hdNews
        components:{hdNews},
        data:{},
    });




</script>
</body>
</html>

效果:

猜你喜欢

转载自www.cnblogs.com/haima/p/10265565.html