以编程方式更改 属性 值或在 Polymer 中对其进行数据绑定

Changing the property value programmatically or data bind it in Polymer

我正在尝试根据从页面 URL 检索到的数字更改 iron-ajax 元素中的 URL。为此,我使用计算的 属性 创建了 URL,它采用了我检索到的数字。
我遇到的问题是我不知道如何以编程方式更改属性中的值(这是将附加到 URL 的数字)。为了解决这个问题,我尝试在 HTML 中设置 Number,然后将其数据绑定到 属性。但是我也无法让它工作。

当我在属性中硬编码 userId 的值时,一切正常,所以我相信错误一定出在我的数据绑定上。如果有人能指出我做错的方向,那就太好了。但是,如果有更好的解决方案,例如以编程方式设置 userId 的值,请告诉我。

<dom-module id="my-profile-view">

  <template>
    <style></style>

    <iron-ajax
      auto
      id="requestSingleUser"
      url="{{url}}"
      handle-as="json"
      last-response="{{response}}"></iron-ajax>

    <span id="stdNr" userId="{{55}}"></span>

  </template>

  <script>
  Polymer({
    is: 'my-profile-view',

    properties: {
      route: Object,

      userId: {
        value: '',
        notify: true
      },

      url: {
        computed: 'computeURL(userId)'
      },

    },

    ready: function() {
      //Get's the URL and strips it down to the nuber
      var getUrl = window.location.href;
      var stdudentNumber = getUrl.split("/").pop();

      //Set the number to then bind it back to the value inside the properties
      var stdId = this.$$("#stdNr");
      stdId.setAttribute('userId','{{20}}');
    },

    computeURL: function(userId) {
      return['http://api.dev/user/' + userId];
    },

  });
  </script>
</dom-module>

有几个问题。

我觉得应该是这样的

<span id="stdNr">[[userId]]</span>

您的 userID 属性 没有正确定义,应该是

 userId: {
   type: String,
   value: ''
 }

然后在你准备好的函数中你会做这样的事情

ready: function() {
  //Get's the URL and strips it down to the nuber
  var getUrl = window.location.href;
  //Set the number to then bind it back to the value inside the properties
  this.userId = getUrl.split("/").pop();
},

最后你计算的函数应该return一个字符串而不是一个数组

computeURL: function(userId) {
  return 'http://api.dev/user/' + userId;

虽然您真的需要将完整的域名放在 url 中,但它不会只是与应用程序其余部分来自的同一域相关吗?

this.userId 的设置将自动使计算的 url 生效