安装 Vue CLI
开始 vue,请先安装 Vue CLI。
在命令行中安装:
yarn global add @vue/cli安装这个新的包vue --version检查其版本
Vue 的两个版本
vue.js 有两个不同的构建版本,可以通过 bootCDN 引入, vue.js(完整版)或vue.runtime.js(只包含运行时版)
- 完整版:同时包含编译器和运行时的版本。
- 编译器:用来将模板字符串编译成为 JavaScript 渲染函数的代码。
- 运行时:用来创建 Vue 实例、渲染并处理虚拟 DOM 等的代码。基本上就是除去编译器的其它一切。
两个版本的不同用法
- vue 的完整版,需要引入 (
vue.js),用 template ,需要编译器。
//main.js
new Vue({
el: "#app",
template: `
<div @click="add">{{n}}<button>+1</button></div>
`,
data: {
n: 0
},
methods:{
add(){
this.n += 1
}
}
})
- vue 的非完整版(运行时版),需要引入 (
vue.runtime.js),用 render,不需要编译器。
// main.js
new Vue({
el: "#app",
render(h){
return h("div", [this.n, h("button", {on:{click:this.add}}, "+1")])
},
data: {
n: 0
},
methods:{
add(){
this.n += 1
}
}
})
或者可以将以下这一段,部署到 demo.vue 新文件中,然后在 main.js 文件中 import
"div", [this.n, h("button", {on:{click:this.add}}, "+1")]
demo.vue 文件
// demo.js
<template>
<div class="red">
{{ n }}
<button @click="add">+1</button>
</div>
</template>
<script>
export default {
data() {
return {
n: 0
}
},
methods: {
add(){
this.n += 1
}
}
}
</script>
<style scoped>
.red{
color: red;
}
</style>
main.js 文件
import Demo from "./demo.vue";
new Vue({
el: '#app',
render(h) {
return h(Demo)
},
})
codesandbox.io
当然,可以直接用 codesandbox.io 来写 Vue 代码
- 打开codesandbox.io,点击 create sandbox
2. 选择点击 Vue
3. 看到如下画面,即可开始你的 vue 代码了