本文介绍了实现 vue-router 后 Vue.js 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来尝试创建单页应用程序的代码.我正在阅读有关 vue 路由器的信息,并尝试将其应用到我的项目中.我不确定代码有什么问题,但我看不到应用程序运行的页面.我在 chrom 控制台上遇到一些错误,但是在我将 vue 路由器添加到我的项目后会发生这种情况.任何帮助修复它?

<html lang="zh-cn"><头><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no"><!-- Bootstrap CSS --><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MujInh2"><link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeDLCWi6HcDUbeDLCWipgin<jwcDubeDLCWipgin<jwcd.;<link href="https://fonts.googleapis.com/css2?family=Courgette&display=swap" rel="stylesheet"><script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"mous>;<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UrksVoyan"></脚本><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og"cross<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script src="https://unpkg.com/vue-router/dist/vue-router.js"></script><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>< SCRIPT SRC = https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" 完整性= SHA512-gZwIG9x3wUXg2hdXF6 + rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew ==" crossorigin = " ></脚本><title>C 安全!</title><身体><风格>h1{字体系列:'西葫芦',草书;}.list-group {最大高度:300px;底边距:10px;溢出:滚动;-webkit-overflow-scrolling:触摸;}#地图 {高度:400px;}</风格><div class="container-fluid bg-light p-0" id="app"><div class="row"><div class="col-sm-12 col-md-12 col-lg-12 p-5"><ul class="nav"><router-link to="/"><li class="nav-item"><a class="nav-link" href="#">首页</a></路由器链接>

<script type="text/x-template" id="search-bar"><div class="row justify-content-center m-0" style="height:100vh;"><div class="col-sm-12 col-md-8 col-lg-8 p-5 mx-auto"><h1 class="mt-5 mb-3 text-center">C</h1><div class="input-group"><input type="email" class="form-control rounded-0" v-on:change="instantSearch()" v-model="q" placeholder="Cerca nelle vicinanze es: Pizzeria"><div class="input-group-append"><button class="btn btn-outline-success rounded-0" v-on:click="instantSearch()">Cerca</button>

<ul v-if="resultSet" class="list-group rounded-0"><small v-if="q" class="list-group-item rounded-0"><a class="text-muted" href="#" v-on:click="resetSearch()">Annnulla</a></small><router-link to="/results"><a v-for="result in resultSet" :key="result.id" v-on:click="expandMap(result.lat, result.lon)" href="#" class="list-group-item rounded-0" :place="result.display_name">{{ result.display_name }}</a></路由器链接><ul class="nav"><li class="nav-item"><a class="nav-link" href="#">FAQ</a><li class="nav-item"><a class="nav-link" href="#">Aggiungi la tua attività</a>

<script type="text/x-template" id="result-detail"><div class="collapse" id="map-collapsable"><div class="row m-0 results-map"><div class="col-sm-12 col-md-8 col-lg-8 p-0" id="map"></div><div v-for="place in placeData" class="col-sm-12 col-md-4 col-lg-4">{{ place.lat }} {{ place.lng }}

<路由器视图></路由器视图>

<!-- 待办事项:Vue 组件 --><script src="app.js"></script></html>

这是 JS vue 代码

window.onload = function(){Vue.component('搜索栏',{模板:'#搜索栏',数据(){返回 {}}});Vue.component('视图结果',{模板:'#result-detail',数据(){返回 {}}});const searchbar = {模板:'搜索栏'}const 结果 = {模板:'视图结果'}const 路由 = [{路径:'/',组件:搜索栏},{路径:'/结果',组件:结果}];const 路由器 = 新的 VueRouter({routes//`routes: routes` 的缩写});const web = new Vue({路由器,el: '#app',数据: {页面数据:[],结果集:[],地点数据:[],q: '',姓名: '',},安装:功能(){//this.initPage();},准备好:函数(){},计算:{},手表: {q: 函数(val, oldVal){this.instantSearch();}},方法: {即时搜索:功能(){axios.get('https://nominatim.openstreetmap.org/search?q='+this.q+'&format=json').then( (places) => {控制台日志(地方);this.resultSet = [];Places.data.forEach((item, i) => {this.resultSet.push(item);});});},重置搜索:函数(){this.resultSet = [];this.q = '';},expandMap:函数(纬度,经度){let collapsable = document.getElementById('map-collapsable');控制台日志(纬度,经度);//$(可折叠).collapse();this.placeData.push({lat: lat, lng: lng});},initMap:函数(数据){}}}).$mount('#app');}

我得到的错误如下:

vue.js:634 [Vue 警告]:属性或方法result"未在实例上定义,但在渲染期间被引用.通过初始化属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件.请参阅:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.(在  中找到)警告@vue.js:634warnNonPresent @ vue.js:2047有@vue.js:2092评估 @ VM258:3vue._render @ vue.js:3551updateComponent @ vue.js:4067获取@vue.js:4478观察者@vue.js:4467mountComponent @ vue.js:4074vue.$mount @ vue.js:9044vue.$mount @ vue.js:11944vue._init @ vue.js:5012vue@vue.js:5078window.onload @ app.js:28加载(异步)(匿名)@ app.js:1vue.js:634 [Vue 警告]:渲染错误:TypeError:无法读取未定义的属性‘display_name’"(在  中找到)警告@vue.js:634logError @ vue.js:1893globalHandleError @ vue.js:1888handleError @ vue.js:1848vue._render @ vue.js:3553updateComponent @ vue.js:4067获取@vue.js:4478观察者@vue.js:4467mountComponent @ vue.js:4074vue.$mount @ vue.js:9044vue.$mount @ vue.js:11944vue._init @ vue.js:5012vue@vue.js:5078window.onload @ app.js:28加载(异步)(匿名)@ app.js:1vue.js:1897 TypeError: 无法读取未定义的属性display_name"在 Proxy.eval (eval at createFunction (vue.js:11649), :3:1557)在 Vue._render (vue.js:3551)在 Vue.updateComponent (vue.js:4067)在 Watcher.get (vue.js:4478)在新的 Watcher (vue.js:4467)在 mountComponent (vue.js:4074)在 Vue.$mount (vue.js:9044)在 Vue.$mount (vue.js:11944)在 Vue._init (vue.js:5012)在新的 Vue (vue.js:5078)logError @ vue.js:1897globalHandleError @ vue.js:1888handleError @ vue.js:1848vue._render @ vue.js:3553updateComponent @ vue.js:4067获取@vue.js:4478观察者@vue.js:4467mountComponent @ vue.js:4074vue.$mount @ vue.js:9044vue.$mount @ vue.js:11944vue._init @ vue.js:5012vue@vue.js:5078window.onload @ app.js:28加载(异步)(匿名)@ app.js:1vue.js:634 [Vue 警告]:找不到元素:#app警告@vue.js:634查询@vue.js:5666vue.$mount @ vue.js:11882window.onload @ app.js:83加载(异步)(匿名)@ app.js:1vue.js:634 [Vue 警告]:属性或方法result"未在实例上定义,但在渲染期间被引用.通过初始化属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件.请参阅:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.(在  中找到)警告@vue.js:634warnNonPresent @ vue.js:2047有@vue.js:2092评估 @ VM258:3vue._render @ vue.js:3551updateComponent @ vue.js:4067获取@vue.js:4478观察者@vue.js:4467mountComponent @ vue.js:4074vue.$mount @ vue.js:9044vue.$mount @ vue.js:11944window.onload @ app.js:83加载(异步)(匿名)@ app.js:1vue.js:634 [Vue 警告]:渲染错误:TypeError:无法读取未定义的属性‘display_name’"(在  中找到)警告@vue.js:634logError @ vue.js:1893globalHandleError @ vue.js:1888handleError @ vue.js:1848vue._render @ vue.js:3553updateComponent @ vue.js:4067获取@vue.js:4478观察者@vue.js:4467mountComponent @ vue.js:4074vue.$mount @ vue.js:9044vue.$mount @ vue.js:11944window.onload @ app.js:83加载(异步)(匿名)@ app.js:1vue.js:1897 TypeError: 无法读取未定义的属性display_name"在 Proxy.eval (eval at createFunction (vue.js:11649), :3:1557)在 Vue._render (vue.js:3551)在 Vue.updateComponent (vue.js:4067)在 Watcher.get (vue.js:4478)在新的 Watcher (vue.js:4467)在 mountComponent (vue.js:4074)在 Vue.$mount (vue.js:9044)在 Vue.$mount (vue.js:11944)在 window.onload (app.js:83)logError @ vue.js:1897globalHandleError @ vue.js:1888handleError @ vue.js:1848vue._render @ vue.js:3553updateComponent @ vue.js:4067获取@vue.js:4478观察者@vue.js:4467mountComponent @ vue.js:4074vue.$mount @ vue.js:9044vue.$mount @ vue.js:11944window.onload @ app.js:83加载(异步)(匿名)@ app.js:1

我不知道为什么,但在我创建组件并尝试使用 vue-router 之前,一切正常.

解决方案

有几个问题:

  1. script type=text/x-template 需要移到 app div 之外.否则,模板将作为 app 模板的一部分进行处理,从而导致您在控制台中观察到的 undefined 错误.

  2. 由于您的 Vue 声明已经指定了 el: #app,您需要删除 .$mount('#app').

  3. 路由路径错误地指定了文字字符串模板:{ template: 'search-bar' }{ template: 'result-detail' }.那应该是 { template: '<search-bar/>'}{ 模板:'<result-detail/>'} 分别.

  4. qresultSet 数据道具应该移到 search-bar 组件中.类似地,placeData 数据道具应该移到 result-detail 组件中.

演示:

window.onload = function(){Vue.component('搜索栏',{模板:'#搜索栏',数据(){返回 {结果集:[],q: '',}}});Vue.component('视图结果',{模板:'#result-detail',数据(){返回 {地点数据:[],}}});const searchbar = {template: '<search-bar/>'}const 结果 = {模板:'<view-result/>'}const 路由 = [{路径:'/',组件:搜索栏},{路径:'/结果',组件:结果}];const 路由器 = 新的 VueRouter({路线//`routes: routes` 的缩写});const web = new Vue({路由器,el: '#app',数据: {页面数据:[],姓名: '',},安装:功能(){//this.initPage();},准备好:函数(){},计算:{},手表: {q: 函数(val, oldVal){this.instantSearch();}},方法: {即时搜索:功能(){axios.get('https://nominatim.openstreetmap.org/search?q='+this.q+'&format=json').then( (places) => {控制台日志(地方);this.resultSet = [];Places.data.forEach((item, i) => {this.resultSet.push(item);});});},重置搜索:函数(){this.resultSet = [];this.q = '';},expandMap:函数(纬度,经度){let collapsable = document.getElementById('map-collapsable');控制台日志(纬度,经度);//$(可折叠).collapse();this.placeData.push({lat: lat, lng: lng});},initMap:函数(数据){}}})}
<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></脚本><script src="https://unpkg.com/vue-router@3.1.6/dist/vue-router.js"></script><风格>h1{字体系列:'西葫芦',草书;}.list-group {最大高度:300px;底边距:10px;溢出:滚动;-webkit-overflow-scrolling:触摸;}#地图 {高度:400px;}</风格><div class="container-fluid bg-light p-0" id="app"><div class="row"><div class="col-sm-12 col-md-12 col-lg-12 p-5"><ul class="nav"><router-link to="/"><li class="nav-item"><a class="nav-link" href="#">首页</a></路由器链接>

<路由器视图></路由器视图>

<script type="text/x-template" id="search-bar"><div class="row justify-content-center m-0" style="height:100vh;"><div class="col-sm-12 col-md-8 col-lg-8 p-5 mx-auto"><h1 class="mt-5 mb-3 text-center">C</h1><div class="input-group"><input type="email" class="form-control rounded-0" v-on:change="instantSearch()" v-model="q" placeholder="Cerca nelle vicinanze es: Pizzeria"><div class="input-group-append"><button class="btn btn-outline-success rounded-0" v-on:click="instantSearch()">Cerca</button>

<ul v-if="resultSet" class="list-group rounded-0"><small v-if="q" class="list-group-item rounded-0"><a class="text-muted" href="#" v-on:click="resetSearch()">Annnulla</a></small><router-link to="/results"><a v-for="result in resultSet" :key="result.id" v-on:click="expandMap(result.lat, result.lon)" href="#" class="list-group-item rounded-0" :place="result.display_name">{{ result.display_name }}</a></路由器链接><ul class="nav"><li class="nav-item"><a class="nav-link" href="#">FAQ</a><li class="nav-item"><a class="nav-link" href="#">Aggiungi la tua attività</a>

<script type="text/x-template" id="result-detail"><div class="collapse" id="map-collapsable"><div class="row m-0 results-map"><div class="col-sm-12 col-md-8 col-lg-8 p-0" id="map"></div><div v-for="place in placeData" class="col-sm-12 col-md-4 col-lg-4">{{ place.lat }} {{ place.lng }}

</script>

This is the code I'm using to try creating a single page app. I'm reading about vue router and I've tried to apply it to my project. I'm not sure what's wrong with the code, but I'm not able to see the page where the app run. I get some errors on chrom console, but this happen after I've added vue router to my project. Any help to fix it?

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <link href="https://fonts.googleapis.com/css2?family=Courgette&display=swap" rel="stylesheet">


    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>

    <title>C safe!</title>
  </head>
  <body>

    <style>
    h1{
      font-family: 'Courgette', cursive;
    }
    .list-group {
      max-height: 300px;
      margin-bottom: 10px;
      overflow:scroll;
      -webkit-overflow-scrolling: touch;
    }
    #map {
      height: 400px;
    }
    </style>
    <div class="container-fluid bg-light p-0" id="app">

      <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12 p-5">
        <ul class="nav">
          <router-link to="/">
            <li class="nav-item">
              <a class="nav-link" href="#">Home</a>
            </li>
          </router-link>
        </ul>
        </div>
      </div>

    <script type="text/x-template" id="search-bar">
      <div class="row justify-content-center m-0" style="height:100vh;">
        <div class="col-sm-12 col-md-8 col-lg-8 p-5 mx-auto">
          <h1 class="mt-5 mb-3 text-center">C</h1>
          <div class="input-group">
              <input type="email" class="form-control rounded-0" v-on:change="instantSearch()" v-model="q" placeholder="Cerca nelle vicinanze es: Pizzeria">
            <div class="input-group-append">
              <button class="btn btn-outline-success rounded-0" v-on:click="instantSearch()">Cerca</button>
            </div>
          </div>
          <ul v-if="resultSet" class="list-group rounded-0">
            <small v-if="q" class="list-group-item rounded-0"><a class="text-muted" href="#" v-on:click="resetSearch()">Annulla</a></small>
            <router-link to="/results">
              <a v-for="result in resultSet" :key="result.id" v-on:click="expandMap(result.lat, result.lon)" href="#" class="list-group-item rounded-0" :place="result.display_name">{{ result.display_name }}</a>
            </router-link>
          </ul>
          <ul class="nav">
            <li class="nav-item">
              <a class="nav-link" href="#">FAQ</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Aggiungi la tua attività</a>
            </li>
          </ul>
        </div>
      </div>
    </script>

    <script type="text/x-template" id="result-detail">
      <div class="collapse" id="map-collapsable">
        <div class="row m-0 results-map">
          <div class="col-sm-12 col-md-8 col-lg-8 p-0" id="map"></div>
          <div v-for="place in placeData" class="col-sm-12 col-md-4 col-lg-4">
          {{ place.lat }} {{ place.lng }}
          </div>
        </div>
      </div>
    </script>

    <router-view></router-view>
    </div>
<!-- TODO: Vue components -->

    <script src="app.js"></script>
  </body>
</html>

This is the JS vue code

window.onload = function(){
  Vue.component('search-bar',{
    template: '#search-bar',
    data(){
      return {}
    }
  });

  Vue.component('view-result',{
    template: '#result-detail',
    data(){
      return {}
    }
  });

  const searchbar = {template: 'search-bar'}
  const result = {template: 'view-result'}

  const routes = [
    {path: '/', component: searchbar},
    {path: '/results', component: result}
  ];

  const router = new VueRouter({
    routes // short for `routes: routes`
  });

  const web = new Vue({
    router,
    el: '#app',
    data: {
      pageData: [],
      resultSet: [],
      placeData: [],
      q: '',
      name: '',
    },
    mounted: function(){
      //this.initPage();
    },
    ready: function(){

    },
    computed: {

    },
    watch: {
      q: function(val, oldVal){
        this.instantSearch();
      }
    },
    methods: {
      instantSearch: function(){
        axios.get('https://nominatim.openstreetmap.org/search?q='+this.q+'&format=json').then( (places) => {
          console.log(places);
          this.resultSet = [];
          places.data.forEach( (item, i) => {
            this.resultSet.push(item);
          });
        });
      },
      resetSearch: function(){
        this.resultSet = [];
        this.q = '';
      },
      expandMap: function(lat, lng){
        let collapsable = document.getElementById('map-collapsable');
        console.log(lat, lng);
        //$(collapsable).collapse();
        this.placeData.push({lat: lat, lng: lng});
      },
      initMap: function(data){

      }
    }
  }).$mount('#app');

}

The errors I get are the following:

vue.js:634 [Vue warn]: Property or method "result" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

(found in <Root>)
warn @ vue.js:634
warnNonPresent @ vue.js:2047
has @ vue.js:2092
eval @ VM258:3
Vue._render @ vue.js:3551
updateComponent @ vue.js:4067
get @ vue.js:4478
Watcher @ vue.js:4467
mountComponent @ vue.js:4074
Vue.$mount @ vue.js:9044
Vue.$mount @ vue.js:11944
Vue._init @ vue.js:5012
Vue @ vue.js:5078
window.onload @ app.js:28
load (async)
(anonymous) @ app.js:1
vue.js:634 [Vue warn]: Error in render: "TypeError: Cannot read property 'display_name' of undefined"

(found in <Root>)
warn @ vue.js:634
logError @ vue.js:1893
globalHandleError @ vue.js:1888
handleError @ vue.js:1848
Vue._render @ vue.js:3553
updateComponent @ vue.js:4067
get @ vue.js:4478
Watcher @ vue.js:4467
mountComponent @ vue.js:4074
Vue.$mount @ vue.js:9044
Vue.$mount @ vue.js:11944
Vue._init @ vue.js:5012
Vue @ vue.js:5078
window.onload @ app.js:28
load (async)
(anonymous) @ app.js:1
vue.js:1897 TypeError: Cannot read property 'display_name' of undefined
    at Proxy.eval (eval at createFunction (vue.js:11649), <anonymous>:3:1557)
    at Vue._render (vue.js:3551)
    at Vue.updateComponent (vue.js:4067)
    at Watcher.get (vue.js:4478)
    at new Watcher (vue.js:4467)
    at mountComponent (vue.js:4074)
    at Vue.$mount (vue.js:9044)
    at Vue.$mount (vue.js:11944)
    at Vue._init (vue.js:5012)
    at new Vue (vue.js:5078)
logError @ vue.js:1897
globalHandleError @ vue.js:1888
handleError @ vue.js:1848
Vue._render @ vue.js:3553
updateComponent @ vue.js:4067
get @ vue.js:4478
Watcher @ vue.js:4467
mountComponent @ vue.js:4074
Vue.$mount @ vue.js:9044
Vue.$mount @ vue.js:11944
Vue._init @ vue.js:5012
Vue @ vue.js:5078
window.onload @ app.js:28
load (async)
(anonymous) @ app.js:1
vue.js:634 [Vue warn]: Cannot find element: #app
warn @ vue.js:634
query @ vue.js:5666
Vue.$mount @ vue.js:11882
window.onload @ app.js:83
load (async)
(anonymous) @ app.js:1
vue.js:634 [Vue warn]: Property or method "result" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

(found in <Root>)
warn @ vue.js:634
warnNonPresent @ vue.js:2047
has @ vue.js:2092
eval @ VM258:3
Vue._render @ vue.js:3551
updateComponent @ vue.js:4067
get @ vue.js:4478
Watcher @ vue.js:4467
mountComponent @ vue.js:4074
Vue.$mount @ vue.js:9044
Vue.$mount @ vue.js:11944
window.onload @ app.js:83
load (async)
(anonymous) @ app.js:1
vue.js:634 [Vue warn]: Error in render: "TypeError: Cannot read property 'display_name' of undefined"

(found in <Root>)
warn @ vue.js:634
logError @ vue.js:1893
globalHandleError @ vue.js:1888
handleError @ vue.js:1848
Vue._render @ vue.js:3553
updateComponent @ vue.js:4067
get @ vue.js:4478
Watcher @ vue.js:4467
mountComponent @ vue.js:4074
Vue.$mount @ vue.js:9044
Vue.$mount @ vue.js:11944
window.onload @ app.js:83
load (async)
(anonymous) @ app.js:1
vue.js:1897 TypeError: Cannot read property 'display_name' of undefined
    at Proxy.eval (eval at createFunction (vue.js:11649), <anonymous>:3:1557)
    at Vue._render (vue.js:3551)
    at Vue.updateComponent (vue.js:4067)
    at Watcher.get (vue.js:4478)
    at new Watcher (vue.js:4467)
    at mountComponent (vue.js:4074)
    at Vue.$mount (vue.js:9044)
    at Vue.$mount (vue.js:11944)
    at window.onload (app.js:83)
logError @ vue.js:1897
globalHandleError @ vue.js:1888
handleError @ vue.js:1848
Vue._render @ vue.js:3553
updateComponent @ vue.js:4067
get @ vue.js:4478
Watcher @ vue.js:4467
mountComponent @ vue.js:4074
Vue.$mount @ vue.js:9044
Vue.$mount @ vue.js:11944
window.onload @ app.js:83
load (async)
(anonymous) @ app.js:1

I don't know why but before I create the components and try to use the vue-router, all was working fine.

解决方案

There are a few problems:

  1. The script type=text/x-templates need to be moved outside of the app div. Otherwise, the template would be processed as part of the app's template, resulting in the undefined errors you observed in the console.

  2. Since your Vue declaration already specifies el: #app, you need to remove .$mount('#app').

  3. The route paths incorrectly specify a literal string template in: { template: 'search-bar' } and { template: 'result-detail' }. That should be { template: '<search-bar />' } and { template: '<result-detail />' } respectively.

  4. The q and resultSet data props should be moved into the search-bar component. Similarly, the placeData data prop should be moved into the result-detail component.

Demo:

window.onload = function(){
  Vue.component('search-bar',{
    template: '#search-bar',
    data(){
      return {
        resultSet: [],
        q: '',
      }
    }
  });

  Vue.component('view-result',{
    template: '#result-detail',
    data(){
      return {
        placeData: [],
      }
    }
  });

  const searchbar = {template: '<search-bar />'}
  const result = {template: '<view-result />'}

  const routes = [
    {path: '/', component: searchbar},
    {path: '/results', component: result}
  ];

  const router = new VueRouter({
    routes // short for `routes: routes`
  });

  const web = new Vue({
    router,
    el: '#app',
    data: {
      pageData: [],
      name: '',
    },
    mounted: function(){
      //this.initPage();
    },
    ready: function(){

    },
    computed: {

    },
    watch: {
      q: function(val, oldVal){
        this.instantSearch();
      }
    },
    methods: {
      instantSearch: function(){
        axios.get('https://nominatim.openstreetmap.org/search?q='+this.q+'&format=json').then( (places) => {
          console.log(places);
          this.resultSet = [];
          places.data.forEach( (item, i) => {
            this.resultSet.push(item);
          });
        });
      },
      resetSearch: function(){
        this.resultSet = [];
        this.q = '';
      },
      expandMap: function(lat, lng){
        let collapsable = document.getElementById('map-collapsable');
        console.log(lat, lng);
        //$(collapsable).collapse();
        this.placeData.push({lat: lat, lng: lng});
      },
      initMap: function(data){

      }
    }
  })

}
<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router@3.1.6/dist/vue-router.js"></script>

<style>
  h1{
    font-family: 'Courgette', cursive;
  }
  .list-group {
    max-height: 300px;
    margin-bottom: 10px;
    overflow:scroll;
    -webkit-overflow-scrolling: touch;
  }
  #map {
    height: 400px;
  }
</style>

<div class="container-fluid bg-light p-0" id="app">

  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12 p-5">
      <ul class="nav">
        <router-link to="/">
          <li class="nav-item">
            <a class="nav-link" href="#">Home</a>
          </li>
        </router-link>
      </ul>
    </div>
  </div>

  <router-view></router-view>
</div>

<script type="text/x-template" id="search-bar">
  <div class="row justify-content-center m-0" style="height:100vh;">
    <div class="col-sm-12 col-md-8 col-lg-8 p-5 mx-auto">
      <h1 class="mt-5 mb-3 text-center">C</h1>
      <div class="input-group">
        <input type="email" class="form-control rounded-0" v-on:change="instantSearch()" v-model="q" placeholder="Cerca nelle vicinanze es: Pizzeria">
        <div class="input-group-append">
          <button class="btn btn-outline-success rounded-0" v-on:click="instantSearch()">Cerca</button>
        </div>
      </div>
      <ul v-if="resultSet" class="list-group rounded-0">
        <small v-if="q" class="list-group-item rounded-0"><a class="text-muted" href="#" v-on:click="resetSearch()">Annulla</a></small>
        <router-link to="/results">
          <a v-for="result in resultSet" :key="result.id" v-on:click="expandMap(result.lat, result.lon)" href="#" class="list-group-item rounded-0" :place="result.display_name">{{ result.display_name }}</a>
        </router-link>
      </ul>
      <ul class="nav">
        <li class="nav-item">
          <a class="nav-link" href="#">FAQ</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Aggiungi la tua attività</a>
        </li>
      </ul>
    </div>
  </div>
</script>

<script type="text/x-template" id="result-detail">
  <div class="collapse" id="map-collapsable">
    <div class="row m-0 results-map">
      <div class="col-sm-12 col-md-8 col-lg-8 p-0" id="map"></div>
      <div v-for="place in placeData" class="col-sm-12 col-md-4 col-lg-4">
        {{ place.lat }} {{ place.lng }}
      </div>
    </div>
  </div>
</script>

这篇关于实现 vue-router 后 Vue.js 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:30
查看更多