为什么我的Vue项目无法加载自定义script.js文件?
问题根源
script.js请求路径错误:你当前使用的/assets/js/script.js路径无法匹配到静态资源,Vue开发服务器未找到对应资源时会默认返回index.html内容,也就是你在控制台看到的模板内容。- 脚本加载时机不合理:全局加载
script.js时登录组件还未完成DOM渲染,就算脚本加载成功也无法绑定到登录页的按钮节点上,交互逻辑不生效。 - 代码存在语法错误:
- login.vue的template末尾多了
</main>和</body>标签,单文件组件模板不需要写外层页面标签,会导致DOM结构异常。 - Vue2组件的响应式数据必须通过
data函数返回,你直接写的datos:{...}不属于合法配置,不会生成响应式数据。 - axios.post是异步请求,你直接判断
if(valor)永远为真,无法正确校验登录结果。
- login.vue的template末尾多了
解决方案
1. 修正静态资源路径
把script.js文件放到项目根目录的public/js文件夹下(没有对应目录就新建),public目录下的资源会直接作为根路径静态资源返回,不会触发index.html fallback。
如果你不想用插件加载脚本,也可以直接在main.js顶部直接引入:
// main.js顶部添加,无需使用load-script插件 import '@/assets/js/script.js'
2. 调整脚本加载时机到登录组件挂载后
删掉main.js中Vue.loadScript相关的代码,改为在login.vue的mounted生命周期中加载,保证DOM渲染完成后再绑定脚本事件,同时修正其他代码错误:
<script> export default { name: 'Login', props: { msg: String }, // 修正响应式数据写法 data() { return { datos: { username:"", password:"", nombres: "", apellidos: "", email:"", id:"" } } }, mounted() { // 组件DOM渲染完成后再加载交互脚本 this.$loadScript("/js/script.js") .then(() => { console.log('登录页脚本加载成功') }) .catch(e => console.error('脚本加载失败', e)) }, methods:{ // 修正异步登录判断逻辑 async login(){ this.datos.username = document.getElementById("user").value; this.datos.password = document.getElementById("pass").value; let user = {username: this.datos.username, password: this.datos.password}; try { const res = await this.axios.post("/autenticar", user); if(res.data) { alert("Datos correctos") } else { alert("Datos incorrectos") } } catch(e) { alert("登录请求失败") console.error(e) } }, register(){ this.datos.nombres = document.getElementById("nombres").value; this.datos.apellidos = document.getElementById("apellidos").value; this.datos.email = document.getElementById("email").value; this.datos.username = document.getElementById("idN").value; this.datos.id = document.getElementById("idN").value; this.datos.password = document.getElementById("idN").value; let usuario = {nombres: this.datos.nombres, apellidos: this.datos.apellidos, email: this.datos.email, username: this.datos.id, password: this.datos.id, _id: this.datos.id}; this.axios.post("/", usuario) .then(res =>{ alert("Usuario creado correctamente! " + res.data ) }).catch(err => console.log(err)); } } } </script>
3. 修正模板语法错误
删掉login.vue的template末尾多余的</main>和</body>标签即可。
内容的提问来源于stack exchange,提问作者Juan Felipe Jaramillo Losada
相关产品推荐
相关产品推荐

