2月10日-vue-cli(4). 项目代码

Profile Picture
- Published on Feb 10, 2020🌏 Public

项目文件

src文件夹是我们重点关注的部分,项目的js入口文件是main.js。该文件会编译后加载到index.html文件中。

components文件夹下一般用来放组件。

assets文件夹放资源文图

核心部分就是public/index.html和src/main.js

重新建立publig/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

写 main.js

import Vue from 'vue'; //通过import加载vue包

new Vue({
  el:"#app",
  data:{
    str:"你好"
  },
  template:`   
  <div  id="app" > 
    <div>1242134</div>
    {{str}}
  </div>
  `
})

改完后会报错,说使用的runtime-only的vue版本。就是不支持template模板的运行时编译。

在可视化界面进行配置,把vue-cli的运行时编译开启就可以了。记得重启项目。

如果不想打开可视化界面,就在项目根目录下建立vue.config.js的文件。

module.exports = {
  runtimeCompiler: true //设定开启运行时编译
}

module.exports作用跟export default类似,他是数据node里面module系统的一种语法。


使用组件形式加载内容

建立App.vue

<!--模板代码写在这里面-->
<template>

    <div id="app">1234</div>
</template>

<script>
export default {
    //组件配置对象额其他部分写到这里
}
</script>

我们写.vue文件,是为了得到一个组件配置对象。

Vue.component('组件名',组件配置对象);

main.js

import Vue from 'vue'
import App from './App.vue' //加载了App这个组件的配置对象
Vue.component("App",App); //注册组件
new Vue({
  el:'#app',
  template:`<App></App>`//使用组件
})

不开启运行时编译的情况下,使用render函数加载App组件

import Vue from 'vue'
import App from './App.vue' //加载了App这个组件的配置对象
//Vue.component("aaaa",App); //注册组件
new Vue({
  el:'#app',
  //无法使用template属性,我们就用render函数构建内容
  render:function(h){
    //return  h('aaaa') //这种方式需要注册组件
    return h(App) //直接将组件配置对象传入h函数,会根据配置对象直接送该组件。
  } 
 // template:`<aaaa></aaaa>`//由于关闭了运行时编译,不允许使用tempalte
})

将不要的删除,将render函数换成表达式写法

import Vue from 'vue'
import App from './App.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})

在App.vue中加载子组件

aa.vue组件

<template>
    <div>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    </div>
</template>
<script>
export default {
    
}
</script>
<template>
    <div id="app">
        {{hello}}
        <aa></aa>
    </div>
</template>

<script>
import aa from './components/aa.vue'
export default {
    components: {
      aa //aa:aa
    }, 
    data(){
       return { hello:'你好'}
    }
}
</script>