VUE實戰技巧

又到了週五,這兩週有點小忙,5.10 母親節那天,我沒有放假,出來打拼嘛,挺辛苦的,剛好月中版本上線,我做的蠻重要的模塊,5.12 就封板了,所以得 5.10 號加了個班,還好可以調休,不然連上半個月還不能休息是有點心累的。公司還行是雙休,項目組也不錯,一般不加班,所以就乘着週五有點自己的時間看看前端的東西,因此有了這篇博文。

基礎環境搭建

官方提示:如果你在 Windows 上通過 minTTY 使用 Git Bash,交互提示符並不工作,必須通過 winpty vue.cmd create hello-world 啓動這個命令

  • 執行 winpty vue.cmd create hello-world
    在這裏插入圖片描述
    因爲重點不在引入一些別的組件直接選擇 default 就可以了。

vue 組件全局註冊

  • Vue 普通組件註冊
    比如有三個組件分別是 Child1.vue 、Child2.vue、Child3.vue 需要註冊到 HelloWorld.vue中

HelloWorld.vue

<template>
  <div class="hello">
     <h1>I am Hello World2</h1>
    <Child1></Child1>
    <Child2></Child2>
    <Child3></Child3>
  </div>
</template>

<script>
import Child1 from "./Child1"
import Child2 from "./Child2"
import Child3 from "./Child3"
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  components:{
    Child1: Child1,
    Child2: Child2,
    Child3: Child3
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
  margin: 40px 0 0;
  color: black;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

要進行三步才能使用,1.引入 2.註冊 3. 使用
在這裏插入圖片描述
如果有第二個 Helloworld 需要使用,那麼多的子組件需要再引用一遍
在這裏插入圖片描述

  • 那麼我們可以很容易想象到Vue 中有個全局註冊的概念,把一個文件價定義爲全局組件即可。放入該文件夾的內容都可變成全局註冊,就不需要重複引用了,類似於全局變量的概念。
    Vue.component() 可全局註冊
    在這裏插入圖片描述
    這裏我們使用vue 提供的API中的第二種方式全局註冊。
    在這裏插入圖片描述

GlobalComponents.js

// 1 - GlobalComponents.js

import Vue from 'vue'

function changeStr(str){
    return str.charAt(0).toUpperCase() + str.slice(1)
}

const requireComponent = require.context('.', false, /\.vue$/)
console.log('requireComponent.keys:', requireComponent.keys())
requireComponent.keys().forEach(fileName => {
    const config = requireComponent(fileName)
    console.log('config:', config)
    const componentName = changeStr(
        fileName.replace(/^\.\//,'').replace(/\.\w+$/, '')
    )
    Vue.component(componentName, config.default || config)
})

將 1 - GlobalComponents.js 引入 main.js 之後註冊 HelloWorld.vue HelloWorld1.vue與 Child1.vue Child2.vue Child3.vue 都不需要在引入,註冊,使用這三步了,只需要使用這一步,因爲已經註冊爲全局組件了。import Global from ‘./components/GlobalComponents’

main.js

import Vue from 'vue'
import App from './App.vue'
import Global from './components/GlobalComponents'

Vue.config.productionTip = false

new Vue({
  Global,
  render: h => h(App),
}).$mount('#app')

目錄結構與註冊後的結果
在這裏插入圖片描述
在這裏插入圖片描述

Render函數 : 拯救繁亂的template

Vue權限控制 : 高精度全局權限控制

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章