Vue组件内定义子组件

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        {{message}}
        <cpn></cpn>
    </div>
    <template id="cpn">
        <div>
            <h2>我是子组件</h2>
            <p>我是内容哈哈哈</p>
        </div>
    </template>
    
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app=new Vue({
            el:'#app',
            data:{
                message:'你好啊!',
                isShow:true
            },
            components:{
                cpn:{
                    template:"#cpn",
                    data(){
                        return {
                            isShow:false
                        }
                    }
                }
            }
        })
    </script>
</body>
</html>

另一种写法:
html只需要一个div的id等于app直接挂载替换

// 使用vue进行开发
import Vue from 'vue'
const App = {
    template: `
    <div>
        <h2>{{message}}</h2>
        <button @click="btnClick">按钮</button>
        <h2>{{name}}</h2>
    </div>
    `,
    data(){
        return {
            message:'hellow webpack',
            name:'coderwhy'
        }
    },
    methods:{
        btnClick(){
            alert('弹出!')
        }
    }
}
new Vue({
    el: "#app",
    template:'<App/>',
    components:{
        App
    }
})

然后就可以直接把这个app对象抽离成另一个js文件,通过import导入
这样就更像现在的vue组件化开发了

发布了41 篇原创文章 · 获赞 0 · 访问量 2801

猜你喜欢

转载自blog.csdn.net/weixin_44614772/article/details/104714320