22.hash、domain、nextTick、ref、require

发布时间 2023-07-06 15:50:44作者: cjl2019
1.hash
默认使用hash模式,url会自带#。另一种模式history模式,url不带#。
//router/index.js
const router = new Router({
  routes,
  // vue-router默认使用hash模式,所以在路由加载的时候,项目中的url会自带#。
  // 如果不想使用#,可以使用vue-router的另一种模式history
  mode: "history"
});

 

2.domain动态拼接url

//http://localhost:8080/home#id1
//协议://主机:端口/路径
document.domain; //主机名:localhoast
window.location.port; //端口号:8080
let newUrl=document.domain+':'+window.location.port+'/mf0100802/'; //localhost:8080/mf0100802/

 

3.this.$nextTick()的用法 

场景:this.$nextTick将操作延迟到DOM更新之后执行
<template>
    <div>
        //<el-button>无效
        <button ref="tar" type="button" name="button" @click="testClick">{{content}}</button>
    </div>
</template>
<script>
export default{
    data(){
        return{
            content:'初始值'
        }
    },
    methods:{
        testClick(){
            this.content = "改变后的值";
            //这时候直接打印的话,由于dom元素还未更新,因此打印的还是之前的值
            console.log("11:", this.$refs.tar.innerText); //输出:初始值
            //dom元素更新后执行
            this.$nextTick(()=>{
                console.log("22:", this.$refs.tar.innerText); //输出:改变后的值
            })
        }
    }
}
</script>

 

4.ref:获取dom元素

获取dom元素 
<template>
    <div>
        <div ref="testDom">获取dom元素</div>
        <button @click="changeColor">更改dom颜色</button>
    </div>
</template>
<script>
export default{
    methods:{
        changeColor(){
            this.$refs.testDom.style.color='red'
        }
    }
}
</script>

 

5.require:动态绑定图片的src,需要用require()包起来,否则img图片无法显示

<template>
    <div>
        <div v-for((item,index) in imgData) :key="index">
            <img :src="item.path" alt="">
        </div>
    </div>
</template>
<script>
export default{
    data(){
        return{
            imgData:[
                {img:require("../assets/1.png"),color:"red"},
                {img:require("../assets/2.png"),color:"blue"}
            ]
        }
    }
}
</script>