Vue 的三种 template 模板写法

目录

1、Vue 完整版写法(一)

2、Vue 完整版写法(二)

3、Vue 非完整版 + .vue 文件


1、Vue 完整版写法(一)

由于 Vue 完整版的组成是由 运行时版 + 编译器,编译器可以解析 HTML 代码,所以支持将 HTML 写在 .html 文件中。

<div id="app">
    {{n}}
    <button @click="add">+1</button>
</div>
<script>    //注意要引入 Vue 完整版
    new Vue({
        el: '#app',    //挂载点,和 $mount() 二选一
        data: { n: 0 },    //data 可以改成函数
        methods:{ add(){} }
    })
</script>

2、Vue 完整版写法(二)

在 Vue 完整版的基础上,将 HTML 写到 options 的 template 属性中。

<div id="app">    <!--注意:该div最终会被替换,最终dom上不会存在一个 id 为 app 的节点-->
</div>

<script>
    new Vue({
        template: `
            <div>
                {{n}}
                <button@click="add">+1</button>
            </div>`,
        data: {n:0},    //data 可以改成函数
        methods: { add(){ this.n+=1; } }
    }).$mount('#app')    //$mount() 相当于 options 的 el 属性
</script>

3、Vue 非完整版 + .vue 文件

由于非完整版没有编译器,所以必能直接编译 HTML,而是需要 render 函数,不过还可以配合 vue-loader 使用。

<!-- child.vue文件内容如下 -->
<template>    <!-- template 标签中的是 xml 语言,并不是 html 语言-->
    <div>
        {{n}}
        <button @click="add">+1</button>
    </div>
</template>
<script>
    export default {
        data() { return{n: 0} },    //data必须为函数
        methods:{ add(){ this.n += 1 } }
    }
</script>
<style>这里写CSS</style>

/*然后在另外一个地方写如下代码*/                    /*或者大致写成这样,这种要 vue-loader*/
import Child from './child.vue'                  import Child from './child.vue'
                                                 <Child />
new Vue({                                        new Vue({
    render: h => h(Child)                            component:{ Child }
}).$mount('#app')                                }).$mount('#app')  
发布了193 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Marker__/article/details/105474740