javascript - Vue.js.数据字段不具有约束力

标签 javascript html vue.js vuejs2 two-way-binding

我对 Vue 元素有以下定义:

new Vue({
  el: "#app",
  data: {
    latitude1: 'a',
    name: 'aa'
  },
  mounted() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        this.latitude1 = position.coords.latitude;
      })
    } else {
      this.latitude1 = "WTF??"
      // this doesn't work either:
      // this.$nextTick(() => { this.latitude1 = "WTF??" })
    }
  },
  methods: {
    // button works... WTF?!?
    doIt() {
      this.latitude1 = "WTF??"
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3147445471031f041f0007" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <div>{{ latitude1 }}: {{ name }}</div>
  <button @click="doIt">Do it</button>
</div>

我可以看到正在填充的位置数据。警报显示纬度,但数据字段 latitude1 的 2 路绑定(bind)不起作用。 我尝试过使用它来存储对象状态,但这也不起作用。

我的html如下:

<div class="form-group" id="app">
 <p>
   {{latitude1}}
 </p>
</div>

最佳答案

在 Vue.js 中要做的事情之一是使用定义的方法来进行响应式属性更改。

这是我为其提供的代码:

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

new Vue({
  el: "#app",
  data: {
    latitude1: 'a',
    name: 'aa'
  },
  mounted: function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        console.log(position.coords.latitude);
        Vue.set(this, 'latitude1', position.coords.latitude);
      }, error, options)
    }
  }
});

我还为导航器查询设置了错误处理程序和选项。要查看结果,请检查控制台。

关于javascript - Vue.js.数据字段不具有约束力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49476396/

相关文章:

javascript - 如何使用 JavaScript 动态创建 UTF 字符

html - Firefox 和 Chrome 不会解码 base64 图像或 pdf 文件

javascript - 带有 html5 音频标签的 Steam 浏览器

javascript - 如何使用 SVG 图形绘制 RGB 颜色选择器渐变

javascript - 使用 v-edit-dialog 时如何停止传播/打开 v-expansion-panel?

vue.js - vue组件: dynamically use router-link or href property

vue.js - 如何使用 Vuetify 在轮播的分隔符上方添加文本?

javascript - 为什么即使使用自定义指令,Angular ng-cloak 也会覆盖我的 ng-show

javascript - 在另一个模块中重用 AngularJS 组件(依赖注入(inject))

javascript - 测试元素标签名称