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>
注意事项:
- 组件里面必须使用函数形式
- 函数式中 function 不能使用箭头函数代替。因为箭头函数没有自己的 this ,会往上一层找对象。