安装vue,因为后续在项目中也会使用vue,所以并不是开发时依赖
npm install vue --save
我们在编译完后会出现如下错误:
这是因为runtime-only ->代码中,不可以有任何的template
runtime-compiler ->代码中,可以有template,因为有compiler可以用于编译compiler
解决方法:添加alias别名来指定
安装vue-loader和vue-template-compiler
npm install vue-loader vue-template-compiler --save-dev
webpack.config.js文件中配置规则
{
test:/\.vue$/,
use:['vue-loader']
}
目前所用到的loader及项目结构如下:
App.vue内容
<template>
<div>
<h2 class="title">{{message}}</h2>
<button @click="btnClick">按钮</button>
<h2>{{name}}</h2>
<Cpn/>
</div>
</template>
<script>
//引入组件
import Cpn from './Cpn';
export default {
name:'App',
data(){
return {
message:'Hello Webpack',
name:'詹姆斯'
}
},
components:{
Cpn
},
methods:{
btnClick(){
}
}
}
</script>
<style scoped>
.title{
color:yellow;
}
</style>>
</style>
cpn文件内容
<template>
<div>
<h2>我是组件CPN</h2>
<h2 class="title">{{cName}}</h2>
</div>
</template>
<script>
export default {
name:'Cpn',
data(){
return {
cName:'组件'
}
}
}
</script>
<style>
.title{
color:pink;
}
</style>
入口文件内容:
// 1、使用common.js的模块化规范
const {add, mul} = require('./js/mathUtils.js')
console.log(add(20, 30));
console.log(mul(20, 30));
//2、使用ES6的模块化的规范
import {name, age, height} from "./js/info";
console.log(name);
console.log(age);
console.log(height)
//3、依赖css文件
require('./css/normal.css')
//4、依赖less文件
require("./css/special.less")
document.writeln("<h2>你好啊</h2>")
//5、使用vue进行开发
// 引入vue
import Vue from 'vue';
//引入app组件
import App from './vue/app.vue';
new Vue({
//el和template的关系:template会替换el
el:'#app',
template:'<App/>',
components:{
App
}
})
页面内容
<body>
<div id="app">
</div>
<script src="./dist/bundle.js"></script>
</body>