首頁  >  文章  >  web前端  >  vue專案中watch的immediate使用

vue專案中watch的immediate使用

php中世界最好的语言
php中世界最好的语言原創
2018-06-09 11:38:0527091瀏覽

這次帶給大家vue專案中watch的immediate使用,vue專案中watch的immediate使用注意事項有哪些,以下就是實戰案例,一起來看一下。

這一點我在專案中也是這麼寫的。例如有請求需要再也沒初始化的時候就執行一次,然後監聽他的變化,很多人這麼寫:

created(){
  this.fetchPostList()
},
watch: {
  searchInputValue(){
    this.fetchPostList()
  }
}

上面的這種寫法我們可以完全如下寫:

watch: {
  searchInputValue:{
    handler: 'fetchPostList',
    immediate: true
  }
}

二、元件註冊,值得借鏡

一般情況下,我們元件如下寫:

import BaseButton from './baseButton'
import BaseIcon from './baseIcon'
import BaseInput from './baseInput'
export default {
 components: {
  BaseButton,
  BaseIcon,
  BaseInput
 }
}
<BaseInput v-model="searchText" @keydown.enter="search" />
<BaseButton @click="search"> <BaseIcon name="search"/></BaseButton>

步驟一般有三部,

第一步,引入、

第二步註冊、

第三步才是正式的使用,

這也是最常見且通用的寫法。但是這種寫法經典歸經典,好多組件,要引入多次,註冊多次,感覺很煩。

我們可以藉助webpack,使用 require.context() 方法來建立自己的(模組)上下文,從而實現自動動態require元件。

想法是:在src資料夾下面main.js中,借助webpack動態將需要的基礎元件統統打包進來。

程式碼如下:

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// Require in a base component context
const requireComponent = require.context(
 ‘./components', false, /base-[\w-]+\.vue$/
)
requireComponent.keys().forEach(fileName => {
 // Get component config
 const componentConfig = requireComponent(fileName)
 // Get PascalCase name of component
 const componentName = upperFirst(
  camelCase(fileName.replace(/^\.\//, '').replace(/\.\w+$/, ''))
 )
 // Register component globally
 Vue.component(componentName, componentConfig.default || componentConfig)
})

這樣我們引入元件只需要第三步驟就可以了:

<BaseInput
 v-model="searchText"
 @keydown.enter="search"
/>
<BaseButton @click="search">
 <BaseIcon name="search"/>
</BaseButton>

三、精簡vuex的modules引入

對於vuex,我們輸出store如下寫:

import auth from './modules/auth'
import posts from './modules/posts'
import comments from './modules/comments'
// ...
export default new Vuex.Store({
 modules: {
  auth,
  posts,
  comments,
  // ...
 }
})

要引入好多modules,然後再註冊到Vuex.Store中~~

精簡的做法和上面類似,也是運用require.context()讀取文件,程式碼如下:

import camelCase from 'lodash/camelCase'
const requireModule = require.context('.', false, /\.js$/)
const modules = {}
requireModule.keys().forEach(fileName => {
 // Don't register this file as a Vuex module
 if (fileName === './index.js') return
 const moduleName = camelCase(
  fileName.replace(/(\.\/|\.js)/g, '')
 )
 modules[moduleName] = {
        namespaced: true,
        ...requireModule(fileName),
       }
})
export default modules

這樣我們只需如下程式碼就可以了:

import modules from './modules'
export default new Vuex.Store({
 modules
})

##四、路由的延遲載入

這一點,關於vue的引入,我之前在vue專案重構技術要點和總結中也提及過,可以透過require方式或import()方式動態載入元件。

{
 path: '/admin',
 name: 'admin-dashboard',
 component:require('@views/admin').default
}

{
 path: '/admin',
 name: 'admin-dashboard',
 component:() => import('@views/admin')
}
載入路由。

五、router key元件刷新

#下面這個場景真的是傷透了許多程式設計師的心...先默認大家用的是Vue-router來實現路由的控制。假設我們在寫一個部落格網站,需求是從/post-haorooms/a,跳到/post-haorooms/b。然後我們驚人的發現,頁面跳轉後資料竟然沒更新? !原因是vue-router"智能地"發現這是同一個元件,然後它就決定要重複使用這個元件,所以你在created函數裡寫的方法壓根就沒執行。通常的解決方案是監聽$route的變化來初始化數據,如下:

data() {
 return {
  loading: false,
  error: null,
  post: null
 }
}, 
watch: {
 '$route': {
  handler: 'resetData',
  immediate: true
 }
},
methods: {
 resetData() {
  this.loading = false
  this.error = null
  this.post = null
  this.getPost(this.$route.params.id)
 },
 getPost(id){
 }
}
bug是解決了,可每次這麼寫也太不優雅了吧?秉持著能偷懶則偷懶的原則,我們希望代碼這樣寫:

data() {
 return {
  loading: false,
  error: null,
  post: null
 }
},
created () {
 this.getPost(this.$route.params.id)
},
methods () {
 getPost(postId) {
  // ...
 }
}
解決方案:給router-view添加一個唯一的key,這樣即使是公用組件,只要url變化了,就一定會重新創建這個組件。

<router-view :key="$route.fullpath"></router-view>
註:我個人的經驗,這個一般應用在子路由裡面,這樣才可以不避免大量重繪,假設app.vue根目錄添加這個屬性,那麼每次點擊改變地址都會重繪,還是得不償失的!

六、唯一組件根元素

場景如下:

(Emitted value instead of an instance of Error)

  Error compiling template:

 

 


  - Component template should contain


  - Component template should contain exactly one 」 element.
    If you are using v-if on multiple elements, use v-else-if

    to chain them instead.

模板中p只能有一個,不能如上面那麼平行2個p。

例如以下程式碼:

<template>
 <li
  v-for="route in routes"
  :key="route.name"
 >
  <router-link :to="route">
   {{ route.title }}
  </router-link>
 </li>
</template>
會報錯!

我們可以用render函數來渲染

functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  <li key={route.name}>
   <router-link to={route}>
    {route.title}
   </router-link>
  </li>
 )
}
七、元件包裝、事件屬性穿透問題##

当我们写组件的时候,通常我们都需要从父组件传递一系列的props到子组件,同时父组件监听子组件emit过来的一系列事件。举例子:

//父组件
<BaseInput 
  :value="value"
  label="密码" 
  placeholder="请填写密码"
  @input="handleInput"
  @focus="handleFocus>
</BaseInput>
//子组件
<template>
 <label>
  {{ label }}
  <input
   :value="value"
   :placeholder="placeholder"
   @focus=$emit(&#39;focus&#39;, $event)"
   @input="$emit(&#39;input&#39;, $event.target.value)"
  >
 </label>
</template>

这样写很不精简,很多属性和事件都是手动定义的,我们可以如下写:

<input
  :value="value"
  v-bind="$attrs"
  v-on="listeners"
>
computed: {
 listeners() {
  return {
   ...this.$listeners,
   input: event => 
    this.$emit('input', event.target.value)
  }
 }
}

$attrs包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定,并且可以通过 v-bind="$attrs" 传入内部组件。

$listeners包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

脚手架与热刷新、热加载

Vue怎样进行局部作用域 & 模块化

以上是vue專案中watch的immediate使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn