情况:使用Element-plus 的时候,按官方例程,若在component mounted()等生命周期情况,无法正确拿到在component以外的变量。
代码如下:
<script setup lang="ts">
var dialogFormVisible = ref(false)
const formLabelWidth = '140px'
return {
dialogFormVisible,
formLabelWidth
}
</script>
<template>
<!-- Form -->
<el-dialog v-model="dialogFormVisible" title="登录">
<el-form :model="form">
<el-form-item label="用户" :label-width="formLabelWidth">
<el-input v-model="v_user" autocomplete="off" />
</el-form-item>
<el-form-item label="密码" :label-width="formLabelWidth">
<el-input v-model="v_pass" autocomplete="off" type="password" />
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button type="primary" @click="dialogFormVisible = false; login()">
登录
</el-button>
</span>
</template>
</el-dialog>
<RouterView />
</template>
<script lang="ts">
export default defineComponent({
data() {
return {
v_user:'',
v_pass:''
}
},
mounted(){
},
methods:{
login(){
console.log(CryptoJS.SHA256(this.v_pass).toString())
}
}
</script>
此时Vite run dev的情况均无报错,build后产生问题,报错:dialogFormVisible is not define.
解决方法:将最上方script标签中的内容写进component(不要忘记return所需要的变量,否则同样拿不到)
export default defineComponent({
setup(){
var dialogFormVisible = ref(false)
const formLabelWidth = '140px'
return {
dialogFormVisible,
formLabelWidth,
}
},
data() {
return {
v_user:'',
v_pass:''
}
},
mounted(){
},
methods:{
login(){
cookie.set('user',this.v_user);
console.log(CryptoJS.SHA256(this.v_pass).toString())
}
}
})
之后build,最后问题解决。注意:最好不要将setup单独写一个script标签里