vue之component中的template另一种定义方式

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .red{
            background:#FF0000;
        }
    </style>
</head>
<body>
<div id="app">
    <like></like>
</div>
<template id="like-component-tpl">
    <button :class="{red: liked}" @click="on_click">{{liked_count}}</button>
</template>
<script src="../lib/vue.js"></script>
<script src="./js/main.js"></script>
</body>
</html>

main.js:

Vue.component('like', {
    template: '#like-component-tpl',
    data: function(){
        return {
            liked_count: 10,
            liked: false
        }
    },
    methods: {
        on_click: function(){
            if(!this.liked){
                this.liked_count++;
                this.liked = true
            }else{
                this.liked_count--;
                this.liked = false;
            }
        }
    }
})

new Vue({
    el: '#app'
})

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue ,一个组件可以调用另一个组件的函数,可以通过以下几种方式实现: 1. 使用 `$refs`:在父组件给子组件添加一个 `ref`,然后通过 `$refs` 来访问子组件的方法。例如: ```vue <template> <div> <child-component ref="childRef"></child-component> <button @click="callChildFunction">调用子组件函数</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { callChildFunction() { this.$refs.childRef.childFunction(); } } } </script> ``` 2. 使用事件:在子组件定义一个触发事件,并在父组件监听该事件来调用子组件的函数。例如: ```vue <!-- ChildComponent.vue --> <template> <div> <button @click="triggerEvent">触发事件</button> </div> </template> <script> export default { methods: { triggerEvent() { this.$emit('child-event'); } } } </script> <!-- ParentComponent.vue --> <template> <div> <child-component @child-event="callChildFunction"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { callChildFunction() { // 调用子组件的函数 } } } </script> ``` 3. 使用 Vuex:如果你使用了 Vuex 来进行状态管理,可以在子组件触发一个 action 来调用其他组件的函数。具体的代码逻辑会根据你的项目结构和需求而有所不同,这里无法提供具体示例。 希望这些方法能够帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值