vue.js模板的定义和使用

    xiaoxiao2023-11-07  148

    这里以点赞模板为例子

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .liked { background: deeppink; } </style> </head> <body> <div id="app"> <like></like> </div> </body> <html> Vue.component('like', { template: '<button :class="{liked: liked}" @click="toogle_like()">? {{like_count}}</button>', data: function() { return { like_count: 10, liked: false, } }, methods: { toogle_like: function() { if(this.liked == false){ this.like_count++; }else{ this.like_count--; } this.liked = !this.liked; } } }) new Vue({ el: '#app' })

    说明一下,那个button太长,有两种方法可以解决这个问题

    使用es语法

    template: ` <button :class="{liked: liked}" @click="toogle_like()"> ? {{like_count}} </button> `,

    在页面定义模板

    <template id="like-component-tpl"> <button :class="{liked: liked}" @click="toogle_like()"> ? {{like_count}} </button> </template> template: '#like-component-tpl',

    单独引用

    上面的component是公共的,所有页面都能改,下面是私有的-

    new Vue({ el: '#seg1', components: { alert: { template: '<button @click="on_click">贪贪贪</button>', methods: { on_click: function () { alert('Yo.'); } } } } })

    这样写就只在id为seg1的标签里面能使用这个component

    如何传值:

    <div id="app1"> <a href="/user/whh">whh</a><br> <alert msg="Muhaha"></alert> </div> Vue.component('alert', { template: '<button @click="on_click">弹弹弹</button>', props: ['msg'], methods: { on_click: function() { alert(this.msg) } } }) new Vue({ el: '#app1' })

    这里是先在vue,js将app1域导入,然后再模板里面定义一个可以使用的属性msg,再props里面指定,然后页面就可以使用alert标签和msg这个属性了

    最新回复(0)