vue新手入门出现function () { [native code] }错误
控制台输出错误:[Vue warn]: Unknown custom element: <p1> - did you register the component correctly?For recursive components, make sure to provide the "name" option.页面提示:function () { [native code] },无法
·
控制台输出错误:
[Vue warn]: Unknown custom element: <p1> - did you register the component correctly?
For recursive components, make sure to provide the "name" option.
页面提示:
function () { [native code] },无法出现我们想要的内容
页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="vue">
<!-- 下面这行代码出错-->
<p1>{{currentTime1}}</p1></br>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var vm=new Vue({
el:"#vue",
data:{
message:"hello world"
},
methods:{
currentTime1: function () {
return Date.now();//返回当前时间戳
}
}
});
</script>
</body>
</html>
综上错误,究其原因就是新人对“计算属性”:computed和“事件处理”:methods傻傻分不清楚。根据官方文档总结如下:
对于任何复杂逻辑,你都应当使用计算属性。其余可以使用methods处理。
https://cn.vuejs.org/v2/guide/computed.html?
所以,下次如果再出现function () { [native code] },请使用对应的方法获取值。
这里的methods方法就应该使用currentTime1()调用,计算属性computed就应该使用currentTime2调用。
完整methods方法和计算属性对比运行代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="vue">
<p1>{{currentTime1()}}</p1></br>
<p1>{{currentTime2}}</p1>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var vm=new Vue({
el:"#vue",
data:{
message:"hello world"
},
methods:{
currentTime1: function () {
return Date.now();//返回当前时间戳
}
},
computed:{ //存在缓存,建议不经常的变化的在次操作
currentTime2:function () {
return Date.now();
}
}
});
</script>
</body>
</html>
页面效果:
更多推荐
已为社区贡献2条内容
所有评论(0)