【vue】常见开发知识点与问题整理(持续更新)

前端开发 作者: 2024-08-20 20:40:01
1.vue双向数据绑定vuex中的state 在vue中, 不允许直接绑定vuex的值到组件中, 若是直接使用, 则会报错 have no setter 方法一: 使用get和set 方法二: 使用w
// 在从组件的computed中
computed: {
    user: {
        get() {
          return this.$store.state.user
        },set(v) {
          // 使用vuex中的mutations中定义好的方法来改变
          this.$store.commit('USER',v)
        }
    }
}
// 在组件中就可以使用
<input v-modle="user" />
// 在组件中绑定
<input v-modle="user" />

// 在computed中获取vuex的值
computed: {
  ...mapState( { user: state => state.user } )
}

// 在组件的watch中观测
watch: {
  'user': {
      deep: true,handler(value) {
        // 使用vuex中的mutations中定义好的方法来改变
          this.$store.commit('USER',value)
      }
  }
}
[{
    path:'/login',meta: {
      title: '登录页面'
    },component:'login'
}]
router.beforeEach((to,from,next) => {
  window.document.title = to.meta.title;
  next()
})
<input name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update"/>
import axios from 'axios'

update(e) {
    let file = e.target.files[0]
    let param = new FormData(); // 创建form对象
    param.append('file',file); // 通过append向form对象添加数据
    param.append('chunk','0'); // 添加form表单中其他数据
    let config = { // 添加请求头
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    };
    axios.post('http://172.19.26.60:8080/user/headurl',param,config)
    .then(response => {
        if (response.data.code === 200) {
            this.ImgUrl = response.data.data;
        }
    })
}
var a = {name:'hehe',age:10};
this.$http.post(this.$sign.config.url.loginUrl,this.$qs.stringify({
    "phone":this.phoneNumber,"vCode":this.loginCode,"smsCode":this.phoneCode    
    })
)
.then(response=>{
    console.log(response.data);
    if(response.data.httpCode == 200){
        
    }else{
        
    }
}) 
this.$axios.post(loginUrl,{
    "email": this.email,"password": this.password
},{
    transformRequest: (data) => {
        return this.$qs.stringify(data)
    },}).then(res => {
    if(res.data.resultCode == RESULT_CODE_SUCCESS){
        console.log('登录成功');
        this.$router.push({name:"home"})
    }else{
        console.log('登录失败');
    }
}).catch(err => {
    console.log('登登录出现错误');
})
//设置cookie,增加到vue实例方便全局调用
Vue.prototype.setCookie = (c_name,value,expiredays) => {
  var exdate = new Date();    
  exdate.setDate(exdate.getDate() + expiredays);    
  document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

//获取cookie
Vue.prototype.getCookie = (name) => {
    var arr,reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)){
        return (arr[2]);
    }   
    return null;   
}

//删除cookie
Vue.prototype.delCookie =(name) => {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = this.getCookie(name);
    if (cval != null){
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }     
}
proxyTable: {
    '/api': {
        target: 'http://api.douban.com/v2',changeOrigin: true,pathRewrite: {
            '^/api': ''
        }
    }
}
proxyTable: {
    '**/*.shtml': {
        target: 'http://192.168.198.111:8080/abc',changeOrigin: true
    }
}
<template>  
  <div class="main-body" :style="{'-webkit-overflow-scrolling': scrollMode}">  
    <v-loadmore :top-method="loadTop" :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" :auto-fill="false" ref="loadmore">  
      <ul class="list" v-for="(val,key) in pageList">  
        <li>  
          <div>我是小11</div>  
          <div>我是小11</div>  
        </li>  
      </ul>  
    </v-loadmore>  
  </div>  
</template>  
<script>  
  import {Loadmore} from 'mint-ui';  
  export default {  
    data:function() {  
      return {  
        searchCondition:{  //分页属性  
          pageNo:"1",pageSize:"10"  
        },pageList:[],allLoaded: false,//是否可以上拉属性,false可以上拉,true为禁止上拉,就是不让往上划加载数据了  
        scrollMode:"auto" //移动端弹性滚动效果,touch为弹性滚动,auto是非弹性滚动  
      }  
    },components: {  
      'v-loadmore':Loadmore  // 为组件起别名,vue转换template标签时不会区分大小写,例如:loadMore这种标签转换完就会变成loadmore,容易出现一些匹配问题  
                              // 推荐应用组件时用a-b形式起名  
    },mounted(){  
      this.loadPageList();  //初次访问查询列表  
    },methods: {  
      loadTop:function() { //组件提供的下拉触发方法  
        //下拉加载  
        this.loadPageList();  
        this.$refs.loadmore.onTopLoaded();// 固定方法,查询完要调用一次,用于重新定位  
      },loadBottom:function() {  
        // 上拉加载  
        this.more();// 上拉触发的分页查询  
        this.$refs.loadmore.onBottomLoaded();// 固定方法,查询完要调用一次,用于重新定位  
      },loadPageList:function (){  
          // 查询数据  
        this.api.PageList(this.searchCondition).then(data =>{  
          // 是否还有下一页,加个方法判断,没有下一页要禁止上拉  
          this.isHaveMore(data.result.haveMore);  
          this.pageList = data.result.pageList;  
          this.$nextTick(function () {  
            // 原意是DOM更新循环结束时调用延迟回调函数,大意就是DOM元素在因为某些原因要进行修改就在这里写,要在修改某些数据后才能写,  
            // 这里之所以加是因为有个坑,iphone在使用-webkit-overflow-scrolling属性,就是移动端弹性滚动效果时会屏蔽loadmore的上拉加载效果,  
            // 花了好久才解决这个问题,就是用这个函数,意思就是先设置属性为auto,正常滑动,加载完数据后改成弹性滑动,安卓没有这个问题,移动端弹性滑动体验会更好  
            this.scrollMode = "touch";  
          });  
        });  
      },more:function (){  
          // 分页查询  
        this.searchCondition.pageNo = parseInt(this.searchCondition.pageNo) + 1;  
        this.api.loadPageList(this.searchCondition).then(data=>{  
          this.pageList = this.pageList.concat(data.result.pageList);  
          this.isHaveMore(data.result.haveMore);  
        });  
      },isHaveMore:function(isHaveMore){  
        // 是否还有下一页,如果没有就禁止上拉刷新  
        this.allLoaded = true; //true是禁止上拉加载  
        if(isHaveMore){  
          this.allLoaded = false;  
        }  
      }  
    }  
  }  
</script>
<div @click="eve"></div>
methods: {
    eve() {
        Hub.$emit('change','hehe'); //Hub触发事件
    }
}
created() {
    Hub.$on('change',(msg) => { //Hub接收事件
        this.msg = msg;
    });
}
// 根组件(this.$root)
new Vue({
 el: '#app',router,render: h => h(App),data: {
  // 空的实例放到根组件下,所有的子组件都能调用
  Bus: new Vue()
 }
})
<div @click="eve"></div>
methods: {
    eve() {
        this.$root.Bus.$emit('change','hehe'); 
    }
}
created() {
    this.$root.Bus.$on('change',(msg) => { //接收事件
        this.msg = msg;
    });
}
npm install --save-dev babel-polyfill
module.exports = {
    entry: {
        app: './src/main.js'
    }
}
module.exports = {
    entry: {
        app: ["babel-polyfill","./src/main.js"]
    }
};
  • require("babel-polyfill");
  • import "babel-polyfill";
{
  "compact": false,"presets": ["env","react","stage-0"],"plugins": [
    "transform-runtime"
  ]
}
{
  "compact": false
}
if(from.name == 'staffInfo' && to.name == 'Login'){
    next({path:'/staffInfo',query:{redirect:from.fullPath}});
}else if(from.name == 'acountFill' && to.name == 'Login'){
    next({path:'/acount/acountFill',query:{redirect:from.fullPath}});
}
if(this.data.fieldType === 'Sig') {
    warn('unimplemented annotation type: Widget signature');
    return false;
}
if(data.fieldType === 'Sig') {
    _this2.setFlags(_util.AnnotationFlag.HIDDEN);
} 
const CMAP_URL = 'https://unpkg.com/pdfjs-dist@2.0.489/cmaps/';
pdfjsLib.getDocument({
    data: pdfData,cMapUrl: CMAP_URL,cMapPacked: true,})
export default {
  init: function (){
    //console.log("初始化百度地图脚本...");
    const AK = "AK密钥";
    const BMap_URL = "https://api.map.baidu.com/api?v=2.0&ak="+ AK +"&s=1&callback=onBMapCallback";
    return new Promise((resolve,reject) => {
      // 如果已加载直接返回
      if(typeof BMap !== "undefined") {
        resolve(BMap);
        return true;
      }
      // 百度地图异步加载回调处理
      window.onBMapCallback = function () {
        console.log("百度地图脚本初始化成功...");
        resolve(BMap);
      };

      // 插入script脚本
      let scriptNode = document.createElement("script");
      scriptNode.setAttribute("type","text/javascript");
      scriptNode.setAttribute("src",BMap_URL);
      document.body.appendChild(scriptNode);
    });
  }
} 
  • 直接使用官网提供的引用地址:http://api.map.baidu.com/api?v=2.0&ak=您的密钥
  • 启用 callback 参数,异步加载必须使用此参数才可以生效
  • 启用 https 配置,通过 s=1 参数实现
  • API版本为2.0,经测试使用,发现3.0版本在HTTPS环境下是有问题的,脚本内部某些请求固定使用HTTP,无法正常使用。
window.scrollTo(100,500);
const router = new VueRouter({
  routes: [...],scrollBehavior (to,savedPosition) {
    // return 期望滚动到哪个的位置
  }
})
  • { x: number,y: number }
  • { selector: string,offset? : { x: number,y: number }} (offset 只在 2.6.0+ 支持)
scrollBehavior (to,savedPosition) {
  return { x: 0,y: 0 }
}
scrollBehavior (to,savedPosition) {
  if (savedPosition) {
    return savedPosition
  } else {
    return { x: 0,y: 0 }
  }
}
scrollBehavior (to,savedPosition) {
  if (to.hash) {
    return {
      selector: to.hash
    }
  }
}
 routes: [
    { path: '/',component: Home,meta: { scrollToTop: true }},{ path: '/foo',component: Foo },{ path: '/bar',component: Bar,meta: { scrollToTop: true }}
  ]
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Home = { template: '<div>home</div>' }
const Foo = { template: '<div>foo</div>' }
const Bar = {
  template: `
    <div>
      bar
      <div style="height:500px"></div>
      <p id="anchor">Anchor</p>
    </div>
  `
}

// scrollBehavior:
// - only available in html5 history mode
// - defaults to no scroll behavior
// - return false to prevent scroll
const scrollBehavior = (to,savedPosition) => {
  if (savedPosition) {
    // savedPosition is only available for popstate navigations.
    return savedPosition
  } else {
    const position = {}
    // new navigation.
    // scroll to anchor by returning the selector
    if (to.hash) {
      position.selector = to.hash
    }
    // check if any matched route config has meta that requires scrolling to top
    if (to.matched.some(m => m.meta.scrollToTop)) {
      // cords will be used if no selector is provided,// or if the selector didn't match any element.
      position.x = 0
      position.y = 0
    }
    // if the returned position is falsy or an empty object,// will retain current scroll position.
    return position
  }
}

const router = new VueRouter({
  mode: 'history',base: __dirname,scrollBehavior,routes: [
    { path: '/',meta: { scrollToTop: true }}
  ]
})

new Vue({
  router,template: `
    <div id="app">
      <h1>Scroll Behavior</h1>
      <ul>
        <li><router-link to="/">/</router-link></li>
        <li><router-link to="/foo">/foo</router-link></li>
        <li><router-link to="/bar">/bar</router-link></li>
        <li><router-link to="/bar#anchor">/bar#anchor</router-link></li>
      </ul>
      <router-view class="view"></router-view>
    </div>
  `
}).$mount('#app')
router.afterEach((to,next) => {
    window.scrollTo(0,0);
});
resolve: {
    extensions: ['.js','.vue','.json'],alias: {
      'vue$': 'vue/dist/vue.esm.js','@': resolve('src')
    }
  }
//例如
src
- components
  - a.vue
- router
  - home
    - index.vue

index.vue 里,正常引用 A 组件:
import A from '../../components/a.vue'
如果设置了 alias 后。
alias: {
 'vue$': 'vue/dist/vue.esm.js','@': resolve('src')
}

引用的地方路径就可以这样了
import A from '@/components/a.vue'
这里的 @ 就起到了【resolve('src')】路径的作用。
npm install --save-dev cross-env
{
  "scripts": {
    "dev1": "export WEBPACK_ENV=production && npx webpack -p",## mac
    "dev1": "set WEBPACK_ENV=production && npx webpack -p",## windows
    "dev2": "cross-env CURRENT_ENV=development webpack-dev-server --inline --progress",## 兼容所有平台
  }
}
console.log(process.env.WEBPACK_ENV)
console.log(process.env.CURRENT_ENV)
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_65710.html