`

Vue的技术细节总结

    博客分类:
  • Vue
 
阅读更多

Vue的版本是^2.6.10

vue-router的版本是^3.0.3

vue-/cli-service的版本是^3.8.0

 

1.

cli创建的默认工程,route对应的component option里面,使用了字符串template, 访问时会报如下错误:

[Vue warn]: You are using the runtime-only build of Vue where the template option is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

 

要修复这个问题,要在vue.config.js里面,添加 runtimeCompiler: true选项。而不是网上说的在webpack.config.js里面配置alias。这个webpack的配置对我生成的项目不起作用。

 

2. 

axios请求本地的mock json,需要把mock文件放在public目录下。比如:

public 

    ---- mock

             ---- list.json

 

src

    ---- components

             ---- MyComponent.vue

 

MyComponent的axios的请求要如下写

axios.get('../../mock/list.json')

 

因为public目录里面存放了不需要修改的静态文件,可以被直接访问。

网上写的放在根目录下的static目录中的方法不起作用。

 

3. 

Debug vue的代码,如果是默认设置,并且浏览器开启了map选项,那么可以在代码里写上

    debugger

浏览器就会在这个命令处停止,然后就可以看到源文件进行debug了。

 

4

用Store模式使用数据时,数组要注意

 

Store:

 

export default {
  isDebug: true,
  /*
   Define the type of {} object to avoid below TS compile error.

   Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
   No index signature with a parameter of type 'string' was found on type '{}'.

   */
  state: {
    dataList: [],
  } as { [key: string]: any },

  setDataList(newDataList: any[]) {
    if (this.isDebug) {
      console.info('setDataList was called');
      console.info('new dataList is ' + JSON.stringify(newDataList));
    }
    this.state.dataList = newDataList;
  },
  ...
};
 

 

Component

<template>
    <div>

        <div v-for="data in dataList">{{data.desc}}</div>
    </div>
</template> 

@Component
  export default class DataComponent {

       _dataList = null;

       sharedStore = Store;

       public get dataList () {
            return this.sharedStore.state.dataList;
       }
  
       methodToSetNewDataList(){
            this.sharedStore.setDataList([...]);
       }
  }

 

 使用computed property的方式,让dataList属性实际上是直接使用Store中的数组。这样,当store的数组被设置成新的数组时,component就可以监听到变化。

 

如果是使用下面这种赋值的方式,Store中的数组被设置成新的数组后,component是无法监听到变化的。

我觉得这个是由于Store中的dataList和component的dataList指向了同一个数组。Store的dataList被设置成新数组了, 只会触发Store的dataList属性的变化。而component的dataList属性引用的仍旧是旧数组,实际没有变化/触发变化。

 

@Component
  export default class DataComponent {

       dataList = null;

       sharedStore = Store;

       created(){
           this.dataList = this.sharedStore.state.dataList;
       }

  }

 

5.

Component的$root对象指向的是根Vue应用。

Component的$parent对象指向的是component所属的父Component。


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics