How to dinamically make computed in Vue.js, under

2019-08-21 09:33发布

I my background is knockout.js. In knockout i can do something like this:

var observable = ko.observable;
var pureComputed = ko.pureComputed;
var observableArray = ko.observableArray;

var koRoles = observableArray([]);
var koUsers = observableArray([]);



function loadUsersFromApi(){
  //assume this is async function
  var users = [{
    name: "this is the name",
    roles: ["role1","role2"]
  },{
    name: "another user",
    roles: ["role1"]
  }];
  for (var i in users)
    extendUser(users[i]);
  koUsers(users)
}

function extendUser(user){
    user.roleSummary = pureComputed(function(){
        return summarizeUserRole(user);
    })
}

function summarizeUserRole(user){
    var roles = koRoles();
    var result = [];
    var userRoles = user.roles;
    for (var i in userRoles){
        var userRole = userRoles[i];
        for (var j in roles)
          if (userRole == roles[j].id){
              result.push(roles[j].name);
              break;
          }
    }
    return result.join(", ");
}

function loadRolesFromApi(){
  //assume this is async function
  var roles = [{
    id: "role1",
    name: "Role 1"
  },{
    id: "role2",
    name: "Role 2",
  }]
  koRoles(roles);
}

ko.applyBindings({
    users: koUsers,
})

loadUsersFromApi();
loadRolesFromApi();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="user-list">
    <table>
        <thead>
          <th>Name</th>
          <th>Roles</th>
        </thead>
        <tbody data-bind="foreach: users">
          <tr>
            <td data-bind="text: name"></td>
            <td data-bind="text: roleSummary"></td>
          </tr>
        </tbody>
    </table>
</div>

i want to highlight the function extendUser(user), in this instance, i can extend the object and put a pure computed in knockout and it will refresh even though in the case that koRoles(roles) is finished later. So i want to know how to do this in Vue.JS. Currently I have something like this:

<td class="common__center-align">{{ item.roleSummary }}</td>

and in my component, i have this:

function extendUser(user){

        user.roleSummary = this.roleSummary(user);

}

and in the component on methods

methods: {roleSummary}

with roleSummary is the same logic as the one in knockout version, but this roleSummary can't become computed property. So, how to make this somewhat computed in Vue.js?

i know another alternative with the following method: - make a component for userRow and settle it inside - make sure roles loaded first then just load user

any other solution? but still i want to know how to make a computed in Vue.js dinamically.

标签: vue.js
0条回答
登录 后发表回答