I would like to share a common url between different components in vuejs
So in my main.js
Vue.prototype.$apiurl = '127.0.0.1:8000/api'
Now in my component i would like to call
console.log("apiurl is", this.$apiurl );
The above doesnt work. How do access global variables in vuejs
Having a dictionary for keeping constants seems more appropriate to me in this case, something like this:
APP_CONSTS = {
API_URL: "127.0.0.1:8000/api"
}
Then accessing it whenever you need, like APP_CONSTS.API_URL.
In some situations you may need to share data between components, in these cases state management comes into play. But it may be an overkill for your case.
Related
I'm using Redux in a vanilla JS project. I have a bunch of small modular UI files and controllers and such. In those UI files I might have code like:
const ExampleForm = function (StoreInstance) {
return $('<form />', {
submit: () => {
StoreInstance.dispatch({
type: 'EXAMPLE_DISPATCH',
post: {
message: $TextareaComponent.val()
}
})
return false
}
})
}
The issue is I have a lot of simple view files like this and many of them are nested and I'm finding it to be ugly and error prone to have the store passed as a param to everything.
For example, I trimmed it for brevity but the form component has form element components such as a textarea. Currently I see two options of managing the Store:
Setting it to window when creating it in my entry file (index.js) and then just accessing Store globally. This seems the nicest, although not "best practice" and makes unit testing and server side rendering a bit harder.
Passing it to every component tediously. This is my example above. This I'd consider as "best practice" but it's pretty annoying to do for every file you make almost.
I'm wondering if there's any alternatives or tricks to passing the store instance. I'm leaning towards just making it global.
You could use the constructor pattern and create every view as new ConnectedView(). The ConnectedView would have a memoized instance of the store (this.store within the view), so it doesn't need to be global.
I'm working on an AngularJS project where there is a .constant() provider to declare some basic information used across the whole project. For example, a definition of cookie name. Ex.:
.constant('appConst', {
cookie: 'CookieName',
...
});
But the same thing can be done by declaring a const, ex.:
const appConst = {
cookie: 'CookieName',
...
}
So, what is the advatage of using the .constant provider instead of just declaring a const? I know one of the reasons is because we don't expect the value to change. But isn't this the same objective of a const?
The new const keyword only makes it so you cannot reassign the variable, it doesn't make any object you initially assign to it immutable. So in your example with:
const appConst = {
cookie: 'CookieName',
...
}
You would still be able to change the value of cookie. You just wouldn't be allowed to do something like this:
appConst = { // My new object };
The values in the angular .constant() can also still be changed, so they're not constant in the common use of the word "constant". At least not when you use it like this:
.constant('appConst', {
cookie: 'CookieName',
...
});
So if you for instance do like this and change the value within a controller
app.controller('myController', function(appConst){
appConst.cookie = 'NewCookieName';
})
the change would be reflected anywhere you inject appConst after this controller was constructed.
You can't "reassign" appConst in this case though, that action would just be ignored, so it is constant in that sense.
1- const is new in ES6, so you may need to transpiler your code for supporting old browsers.
2- const is block-scoped, so within a scenario, you define a constant in A.js, will be not able to use it at B.js unless you're using a module bundler, so we went back to the topic 1-.
The main purpose of AngularJS having this native is to able you to share it between controllers, services, and directives, using its dependency injection system.
I am creating a vue webapp, I have few pages with Dynamic content and also few pages which has mostly static content. I want to move all these static strings to one place.
One option can be to use vue-i18n or vue-multilanguage, these gives support to have content files like this, but I really have no use case of support of multiple languages, so it also seems a bit over kill to me.
Another option can be to have a vuex store for all the strings, vuex I am already using for state management.
What can be good approach to do this.
I am not aware of a standard way of doing this, also this would be applicable to all the web frameworks. That said it is an interesting and valid problem.
If I had to do something about it:
I would want these strings to be available everywhere.
I would prefer not having to import these strings in all the components and each time I needed to use them.
I would want the storage space to be descriptive so that I don't have to go back and forth to check what I want to import. [The toughest part in my opinion]
To achieve 1, we can use:
Vuex
A services/some.js file which exports an object.
Plugins
I would go with plugins because:
I can get the strings by merely using this in a component, Vue.use(plugin) prevents the same plugin getting used twice, and at the same time achieve all the points (3rd will still be a tough nut to crack). Only disadvantage that I know of it might clutter the vue-instance.
So plugin can be designed like:
// stringsHelperPlugin.js
const STRING_CONST = {
[component_1_Name]: {
key1: val1,
key2: val2,
....
},
[component_2_Name]: {
key1: val1,
key2: val2,
....
},
...
}
StringConst.install = function (Vue, options) {
Vue.prototype.$getStringFor = (componentName, key) => {
return STRING_CONST['componentName'][key]
}
}
export default StringConst
in main.js this can be used like:
import StringConst from 'path/to/plugin'
Vue.use(StringConst)
and you could use this in a component template like so:
<div>
{{ $getStringFor(<component_1_name>, 'key1') }}
</div>
You can use something like this.$getStringFor(<componentName>, key) in a method. Pretty much everything that vuejs to has to offer.
Why I call the 3rd point hardest is: Maintainance if you ever change component names, you might also have to change it in the object returned by the plugin. This problem again, can be handled in many ways.
You can make an npm module with JSON files containing your strings
If you don't use vuex in your project, put your content in some javascript files which will be basically objects with all your static content and import them where you need just like Belmin menionted I am using Vue js and python flask as my backend. I want to have some local variable set. How can it be done?
A similar approach can be used for urls, configurations, errors etc.
If you use vuex, centralize everything there and make getters which you can use in each of your components.
When I init my vue.js 2.0 app I make window.User object.
That's all going well. Then in some components I'm using it in my
templates:
v-if="this.User.role == 2"
So in some component's this is working and in some not -_- (Cannot read property 'role' of undefined). How is that even possible? In the component's where this is not working I've tried this:
created() {
alert(window.User.role);
}
And the proper result shows up! But in the template it's not working. What could be going on here. Very very frustrating thing.
In my bootstrap.js:
window.User = Laravel.user;
I register all my components the same way:
Vue.component('corporations', require('./components/corporation/Corporations.vue'));
If User is acting like a global variable that you want access to in all components and you want it to be reactive, you can add it to the root Vue's data and then refer to it everywhere else as this.$root.User.
You can also use a mixin to declare a computed that makes it available on all components that use the mixin. Like this:
var mixin = {
computed: {
User: function () { return window.User; }
}
}
The mixin is probably a better route to go.
I want to store a private variable on each DS.Model. Its purpose is to store a pending callback (in case I want to cancel it).
I have tried this (and it works):
DS.Model.reopen({
init() {
let _pending; // my private var
this._getPending = () => _pending; // get private var
this._setPending = callback => _pending = callback; // set private var
this._super(...arguments);
}
});
I have placed this in an initializer, and it works as I expect it to.
My questions are: Is this a good practise? is it likely to mess anything up? ...and, is there a better way?
Personally, I'm happy with the way it works.. but I'm not sure if its the "Ember" way. This is going to go into an Ember-cli addon, so I would like it to be the most "best practise" as possible. (the _getPending/_setPending method are only to be used internally within the addon.)
Here are my 2 cents on this. I would say no it is not a good practice, but it should be okay since they are just Ember Objects. The question here is what is Ember data model used for? From doc it says:
"Models are objects that represent the underlying data that your application presents to the user."
By definition this is not what they are designed for, so just because you are able to it does not mean that you should use them like this.
Pending callback so it can be canceled? Ember model API has defined state objects that can be used for this purpose. http://emberjs.com/api/data/classes/DS.Model.html Flags like isDeleted, isValid, isNew...gives all possible state.
I would place them in router actions where they are easy tested with integration tests.
You can check this screencast that explains them:
https://www.emberscreencasts.com/posts/102-ember-data-20-model-states-and-flags
Hope it helps.