Vue el与data的两种写法

2024-03-12 241 0

1. el 指定容器的方式

第一种:

<!-- vue模板容器 -->
<div id='root'>
    <h1>{{ msg }}</h1>
</div>
<script>
    // 创建vue实例
    new Vue({
        el: '#root',
        data: {
            msg: 'hello vue'
        }
    });
</script>

第二种:

<!-- vue模板容器 -->
<div id='root'>
    <h1>{{ msg }}</h1>
</div>
<script>
    // 创建vue实例
    const vm = new Vue({
        el: '#root',
        data: {
            msg: 'hello vue'
        }
    });
    //挂载
    vm.$mount('#root');
</script>

2. data的两种写法

第一种:对象形式

<!-- vue模板容器 -->
<div id='root'>
    <h1>{{ msg }}</h1>
</div>
<script>
    // 创建vue实例
    new Vue({
        el: '#root',
        data: {
            msg: 'hello vue'
        }
    });
</script>

第二种:函数形式

<!-- vue模板容器 -->
<div id='root'>
    <h1>{{ msg }}</h1>
</div>
<script>
    // 创建vue实例
    new Vue({
        el: '#root',
        data: function() {
            //此处this是vue实例对象
            return {
                msg: 'hello vue'
            }
        }
    });
    //或
    new Vue({
        el: '#root',
        data() {
            return {
                msg: 'hello vue'
            }
        }
    });
</script>

注意事项:

  1. 组件里面必须使用函数形式
  2. 函数式中 function 不能使用箭头函数代替。因为箭头函数没有自己的 this ,会往上一层找对象。

相关文章

Vue 过滤器
Vue 自定义指令
Vue key的作用与原理
Vue 计算属性和监听属性
Vue MVVM与数据代理
vue-codemirror编辑器使用(vue3)

发布评论